问题
I have a text input that need an url as value (complete of http://) and I want that if the user don't writes it himself if gets added automatically. My code as follows,
jQuery
$('.txtUrl').keypress(function(e) {
if(e.keyCode == 13) {
var ini = $(this).val().substring(0,3);
if (ini === 'http'){
$.noop()
}
else {
// get value from field
var cur_val = $(this).val();
// do with cur_val
$(this).val('http://' + cur_val);
}
}
});
HTML
<input type="text" class="txtUrl" />
Problem in Fiddle
回答1:
You're comparing http
to the three first characters (substring(0,3)
) of the text which, of course, never will be true. Change it to:
var ini = $(this).val().substring(0, 4);
回答2:
http://jsfiddle.net/bitsmix/jMH9b/
if ($(this).val().match(/^http/))
regex always better :)
来源:https://stackoverflow.com/questions/7817636/jquery-add-http-as-prefix-to-text-input-if-there-is-none