我想自动将http://
添加到文本框的值中。
例如,cateno.no
应该变为http://cateno.no
,但http://google.com
应该保持不变。
这是HTML:
<input id="urlBanner" type ="text" style ="width:450px;" maxlenght="100" />
答案 0 :(得分:7)
您可以绑定input
的{{3}}事件并评估值:
$(document).ready(function () {
$("#urlBanner").change(function() {
if (!/^http:\/\//.test(this.value)) {
this.value = "http://" + this.value;
}
});
});
示例: change
或者,如果您不喜欢正则表达式,可以使用http://jsfiddle.net/andrewwhitaker/gnHLz/:
$(document).ready(function () {
$("#urlBanner").change(function() {
if (this.value.indexOf("http://") !== 0) {
this.value = "http://" + this.value;
}
});
});
示例: indexOf
答案 1 :(得分:3)
我会对Andrew Whitaker的正则表达式示例稍作修改,以便考虑https网址,否则https://test.com会以http://为前缀,看起来像http://https://test.com
$(document).ready(function () {
$("#urlBanner").change(function() {
if (!/^https*:\/\//.test(this.value)) {
this.value = "http://" + this.value;
}
});
});
答案 2 :(得分:1)
处理某些事件,可能是change
,并在当前值与正则表达式不匹配时添加字符串:
$(document).ready(function() {
$('#urlBanner').bind('change', function() {
var $this = $(this);
if(!/^http:\/\//.test($this.val()) {
$this.val('http://' + $this.val);
}
});
});
答案 3 :(得分: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})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(val);}, 'Please enter valid URL');