18

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

Code I'm using:

function limitText(field, maxChar){
    if ($(field).val().length > maxChar){
       $(field).val($(field).val().substr(0, maxChar));
    }
}

Event is onkeyup. When I type some text in input field cursor stays on the end of text but focus is backed on start of the text so I can't see cursor.

What can be a problem.

Browser is FF, on IE and chrome it is working correctly

2 Answers 2

44

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);
}
Sign up to request clarification or add additional context in comments.

Comments

7

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

1 Comment

Best way in JQuery I found to do this ! Cool !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.