views:

1132

answers:

3

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?

+4  A: 

The attribute you're looking for is maxlength, not max_length. See here.

John Feminella
Sorry, I should have included the fact that you can't set "maxlength" dynamically in IE.
peirix
+2  A: 

If you're using jQuery then why not make full use of its abstractions?

E.g.

Instead of:

$("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");
}

Do this:

$('input#title').attr('maxLength','25').keypress(limitMe);

function limitMe(e) {
    if (e.keyCode == 8) { return true; }
    return this.value.length < $(this).attr("maxLength");
}


Edit: The reason it's not working in IE is probably because of how you attached the 'onKeyPress' handler, via setAttribute. - This isn't the proper way to register event handlers.

J-P
and I found that jQuery's attr() actually manage to set maxlength the proper way, so I don't have to use my own function. Excellent! Thanks, man (:
peirix
A: 

Don't forget though that if you are setting the maxlength via JavaScript, someone else could just as easily change the maxlength to whatever they like. You will still need to validate the submitted data on the server.

Ian Oxley