jQuery将http://添加为文本输入的前缀(如果没有) [英] jQuery Add http:// as prefix to text input if there is none

查看:138
本文介绍了jQuery将http://添加为文本输入的前缀(如果没有)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本输入需要一个URL作为值(完整的http://),我希望如果用户不自己写入,如果自动添加。我的代码如下,

jQuery

  $('。txtUrl ').keypress(function(e){
if(e.keyCode == 13){
var ini = $(this).val()。substring(0,3);
if(ini ==='http'){
$ .noop()
}
else {
//从字段$ b中获取值$ b $ var cur_val = $ (this).val();
//用cur_val做
$(this).val('http://'+ cur_val);
}
}
});

HTML

 < input type =textclass =txtUrl/> 

小提琴问题

解决方案

您正在比较 http 到文本的三个第一个字符( substring(0,3)),这当然永远不会是真的。将其更改为:

  var ini = $(this).val()。substring(0,4); 


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

解决方案

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);

这篇关于jQuery将http://添加为文本输入的前缀(如果没有)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆