Jquery limit text in input box

前端 未结 2 1982
你的背包
你的背包 2021-01-08 00:45

I want to limit number of chars in input text field.

Code I\'m using:

function limitText(field, maxChar){
    if ($(field).val().length > maxChar)         


        
相关标签:
2条回答
  • 2021-01-08 01:28

    you can also do it like this:

    <input type="text" name="usrname" maxlength="10" />
    

    to achieve this with jQuery, you can do this:

    function limitText(field, maxChar){
        $(field).attr('maxlength',maxChar);
    }
    
    0 讨论(0)
  • 2021-01-08 01:44

    Your code is working in FF. Here is slightly modified version of your code:

    $('input.testinput').on('keyup', function() {
        limitText(this, 10)
    });
    
    function limitText(field, maxChar){
        var ref = $(field),
            val = ref.val();
        if ( val.length >= maxChar ){
            ref.val(function() {
                console.log(val.substr(0, maxChar))
                return val.substr(0, maxChar);       
            });
        }
    }
    

    Demo

    0 讨论(0)
提交回复
热议问题