如果无效,则检测输入值并修改值

时间:2012-05-24 01:48:40

标签: jquery jquery-validate html-form html-input

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

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

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

谢谢你, CampSoup1988

1 个答案:

答案 0 :(得分: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());
        }
    }

}