2012-06-13 27 views
1

如何限制为4个数字/位数的输入,但如果输入文本,则字符长度是无限的?jQuery将限制数字/数字限制为4,但文本可以是无限长度

最后的工作代码:

function isNumber (o) { 
    return ! isNaN (o-0); 
} 

$("#txt").keyup(function(e){ 
    txtVal = $(this).val(); 
    if(isNumber(txtVal) && txtVal.length>4) 
    { 
     $(this).val(txtVal.substring(0,4)) 
      $(".error").html("4 Numbers Only").show(); 
     return false; 
    } 
}); 
}); 

回答

7

Live Demo

HTML

<input id="txt1" type="text" name="usrname" />​ 

JAVASCRIPT

function isNumber (o) { 
    return ! isNaN (o-0); 
} 

$("#txt1").keyup(function(e){ 
txtVal = $(this).val(); 
if(isNumber(txtVal) && txtVal.length>4) 
{ 
    $(this).val(txtVal.substring(0,4)) 
} 
}); 
+0

初等小费。但是,这是如何回答Q? –

+0

你说得对,谢谢。我已经更新了我的答案。 – Adil

+0

停止投票的理由? – Adil

2

您可以检查该值是否为数值,何时有超过4个字符触发验证。

$("#yourField").change(function(e){ 
    if(isNaN($(this).val()) && $(this).val().length > 4) 
    { 
     //trigger validation 
    } 
}); 
0

HTML

<input type="text" class="numeric" /> 

JQUERY

$('.numeric').keypress(function(e) { 

var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/); 
if (verified || e.delegateTarget.value.length>3 || e.ctrlKey ==true) { if(e.which!=8){e.preventDefault();}} 

}).on('paste',function(e){ e.preventDefault();}); 

工作实施例

http://jsfiddle.net/nadeemmnn2007/C4Y99/52/

+0

请检查演示 –