将输入框的长度限制为16

时间:2017-09-04 19:30:13

标签: javascript jquery html

我想将输入框的最大长度限制为16个字符,但破折号和空格不应包含在计数中。 到目前为止,这是我的代码

JS

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

    var xcode = (e.which) ? e.which : e.keyCode;
    var maxlength = $('.cardtb').attr('maxlength', '16');

    var regex = new RegExp("[0-9\- ]");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);

    if (regex.test(str)) {
        return true;
    }

    e.preventDefault();
    return false;

});

HTML

<input type="text" id="sf-cardno" class="tb cardtb rtb numericSpaceDash" autocomplete="off" name="cardno" maxlength="16"/>

1 个答案:

答案 0 :(得分:3)

好像你只需从值中删除空格和破折号,并检查它的长度

&#13;
&#13;
$('.numericSpaceDash').on('keypress', function(e) {
    if ( [' ','-'].includes(e.key) ) {
          // do something if space or hyphen pressed
    } else if ( this.value.replace(/(\s|\-)/g,'').length > 15 ) {
        e.preventDefault();
    } else {
        $('#count').html( this.value.replace(/(\s|\-)/g,'').length +1 )
    }
    
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="sf-cardno" class="tb cardtb rtb numericSpaceDash" name="cardno" />
<br />
Count : <span id="count"></span>
&#13;
&#13;
&#13;

请注意,jQuery会对e.which进行规范化,您无需检查它。

相关问题