Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery limit text in input box

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

like image 602
kukipei Avatar asked Sep 13 '12 16:09

kukipei


People also ask

How do I limit text length in jquery?

Limit character input in the textarea including count. JavaScript Code : var maxLength = 15; $('textarea'). keyup(function() { var textlen = maxLength - $(this).

How do I limit the number of characters in an input field?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

How can I count the number of characters in a textbox using jquery?

length; document. getElementById(displayto). innerHTML = len; } </script> <textarea id="data" cols="40" rows="5" onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br> <span id="charcount">0</span> characters entered.

How do I count characters in a textarea jquery?

<textarea id="field" onkeyup="countChar(this)"></textarea> function countChar(val){ var len = val. value. length; if (len >= 500) { val. value = val.


1 Answers

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);
}
like image 149
Ties Avatar answered Sep 28 '22 22:09

Ties