David David - 4 months ago 33
jQuery Question

jquery: How can I set in each input his maxlength value with data-val-length-max value?

I have a form which I want o set data-val-length-max attribute to MAXLENGTH attribute in jquery.

I have next input:

<input type="text" id="name" data-val-length-max="20">
<input type="text" id="lastname" data-val-length-max="10">

when page is loading I need to do that operation. I am executing next jquery:

$("input").attr("maxlength", $("input").attr("data-val-length-max"));

and maxlength is set as the value of first input .... in this case (name maxlength).

How can I do each input set maxlength with his own data-val-length-max value?


jQuery's attr() only gets the attribute for the first element in the collection, from the documentation

Get the value of an attribute for the first element in the set of matched elements

If you want to change the attribute of all the elements in the collection, you'd have to iterate, and a good way to do that would be to use a callback in attr()

$("input").attr("maxlength", function() {
    return  $(this).attr("data-val-length-max");