jQuery Add http:// as prefix to text input if there is none

此生再无相见时 提交于 2019-12-11 11:47:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!