Bagzli Bagzli - 7 months ago 26
Javascript Question

JQuery .each function not working

I am trying to understand why the following doesn't work:

function SetMaxLength() {
var form = $("body").find("form");
form.each(function () {
var elements = $(this).find("input");
elements.each(function() {
var attr = $(this).attr('data-val-maxlength-max');
if (typeof attr !== typeof undefined && attr !== false) {
$(this).attr('maxlength', attr.value);
}
});
});
}


<form action="/go/somewhere" autocomplete="off" class="form-one" method="post" role="form" novalidate="novalidate">
<input data-val-maxlength="Invalid Email" data-val-maxlength-max="254" type="text" value="">
</form>


when I step through it, it finds 1 form but then on the each part it just skips it, steps over it.

Basically all it is suppose to do it when it sees
data-val-maxlength-max
attribute, it is suppose to take its value and inject
maxlength
attribute in the element.

JsFiddle: https://jsfiddle.net/j04vue8r/3/

Answer

Since you already have jQuery included in your page, it's better to rewrite your code and make it more "jQuery style".

Here we go:

$('[data-val-maxlength-max]').each(function(){
  $(this).attr('maxlength', $(this).data('val-maxlength-max'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/go/somewhere" autocomplete="off" class="form-one" method="post" role="form" novalidate="novalidate"> 
  <input data-val-maxlength="Invalid Email" data-val-maxlength-max="254" type="text" value="">
</form>