Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting maxlength using javascript

I'm trying to set the maxlength on input fields dynamically using JavaScript. Apparently that is a problem in IE, and I found part of the solution.

$("input#title").get(0).setAttribute("max_length", 25);
$("input#title").get(0).setAttribute(
                        "onkeypress", 
                        "return limitMe(event, this)");

function limitMe(evt, txt) {
    if (evt.which && evt.which == 8) return true;
    else return (txt.value.length < txt.getAttribute("max_length");
}

It works in Firefox, but not in IE for some reason. However, it works on input fields set like this:

<input type="text" max_length="25" onkeypress="return limitMe(event, this);"/>

But since the input fields are created dynamically, I can't do this... Any ideas?

like image 297
peirix Avatar asked Mar 11 '09 09:03

peirix


1 Answers

All the answers here relies on keypress/paste events. Here is my solution using the input event:

$('input').on('input', onInput);

var inputValue = '';

function onInput(e) {
    if(e.currentTarget.value.length > 30) {
        e.currentTarget.value = titleValue;
        return;
    }

    inputValue = e.currentTarget.value;
}
like image 168
adriendenat Avatar answered Sep 28 '22 08:09

adriendenat