2012-01-31 28 views
0

文本框用户输入我要在前面加上自动向http://一个文本框的值如何自动添加字符串的“http://”时的jQuery

例如,cateno.no应该成为http://cateno.no,但http://google.com应该。保持不变

这里的HTML:

<input id="urlBanner" type ="text" style ="width:450px;" maxlenght="100" /> 
+1

你想要什么时候检查? – 2012-01-31 02:16:45

回答

7

你可以绑定到change事件为input和评估值:

$(document).ready(function() { 
    $("#urlBanner").change(function() { 
     if (!/^http:\/\//.test(this.value)) { 
      this.value = "http://" + this.value; 
     } 
    }); 
}); 

例子:http://jsfiddle.net/andrewwhitaker/gnHLz/

或者,如果你不喜欢的正则表达式,你可以使用indexOf

$(document).ready(function() { 
    $("#urlBanner").change(function() { 
     if (this.value.indexOf("http://") !== 0) { 
      this.value = "http://" + this.value; 
     } 
    }); 
}); 

例子:http://jsfiddle.net/andrewwhitaker/fYRUW/

+0

没有足够的jQuery! ;) – Ryan 2012-01-31 02:18:29

+0

感谢你的地狱我。 – minh 2012-01-31 02:51:05

+0

@minh:没问题。如果有帮助,请“接受”答案! – 2012-01-31 02:52:58

1

处理一些事件,可能是change,并且前置的字符串,如果当前值不匹配正则表达式:

$(document).ready(function() { 
    $('#urlBanner').bind('change', function() { 
     var $this = $(this); 

     if(!/^http:\/\//.test($this.val()) { 
      $this.val('http://' + $this.val); 
     } 
    }); 
}); 
+0

感谢你的地狱我。 – minh 2012-01-31 02:51:22

1
jQuery.validator.addMethod("complete_url", function(val, elem, params) { 
// if no url, don't do anything 
if (val.length == 0) { return true; } 
// if user has not entered http:// https:// or ftp:// assume they mean http:// 
if(!/^(https?|ftp):\/\//i.test(val)) { 
    val = 'http://'+val; // set both the value 
    $(elem).val(val); // also update the form element 
} 
else if(/^(https?|ftp):\/\//i.test(val)) { // set both the value 
    $(elem).val(val); // also update the form element 
} 
// now check if valid url 
return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'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ter valid URL'); 
2

我会做轻微的改动,安德鲁·惠特克的正则表达式的例子来解释HTTPS URL中,否则https://test.com会以http前缀:/ /并且看起来像

$(document).ready(function() { 
    $("#urlBanner").change(function() { 
     if (!/^https*:\/\//.test(this.value)) { 
      this.value = "http://" + this.value; 
     } 
    }); 
});