【问题标题】:Detect input value and modify value if not valid检测输入值,如果无效则修改值
【发布时间】:2012-05-30 14:27:36
【问题描述】:

我认为这是一个简单的问题,但是我找不到解决方案。

我有一个由 jQuery Validator 验证的表单。我有一个 html 输入类型,它是 url,并使用 jQuery 来验证它是一个 url。我想编写一个脚本来检测输入的值是否以 http:// 或 https:// 开头,如果不以其中任何一个开头,则自动将 http:// 添加到开头价值。另外,我希望脚本检测表单值是否为空,如果为空,则不添加 http://

<input name="Website" type="url" id="Website" >

谢谢你, CampSoup1988

【问题讨论】:

  • 我正在尝试使用 .change 和 .trigger 函数编写脚本。

标签: jquery jquery-validate forms html-input


【解决方案1】:

试试这个...

http://jsfiddle.net/KMc8x/4/

$(document).ready(function () {

        $('input#Website').bind('change',function() {
               addhttp();
        });

        $('input#Website').keyup(function() {
               addhttp();
        });    
});

function addhttp () {
    // if user has entered 4 or more characters
    if ($("input#Website").val().length >= 4) {

        // if user's first 4 characters are not http
        if ($("input#Website").val().indexOf("http") == -1) {
            $("input#Website").val('http://' + $("input#Website").val());
        }

    // if user has entered 1-4 characters
    } else if ($("input#Website").val().length > 0 && $("input#Website").val().length < 5) {

        // if user's first 4 characters do not have h
        if ($("input#Website").val().indexOf("h") == -1) {
            $("input#Website").val('http://' + $("input#Website").val());
        }
    }

}

【讨论】:

  • 太棒了!谢谢@Supercoolville!这正是我所要求的!
猜你喜欢
  • 2023-03-24
  • 1970-01-01
  • 2018-02-07
  • 2019-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多