Can not add html tag attribute to 2 different elements at same time

Hi all!
For a big form I want to add an attribute “maxlength=x” to all textfields

<input type="text" maxlength=5...>

and 10 to one textarea, different values.
codepen
Otherwise I have to add maxlenght to all tags manually in html - not efficient (imagine you had 50 textfields…), can not be achived by css. So I have to inject this attribute by JS.

Both parts seperateley work if 1 is commented out, but not together.

<script>
// part 1: adding maxlength=5 to all textfields, with css not possible
const textfields = document.getElementsByTagName("input");
// makes an array of all 2 textfields
for (let i in textfields) {
  textfields[i].setAttribute("maxlength", "5");
 }

// part 2: adding maxlength=10 to the textarea
const textarea = document.getElementsByTagName("textarea")[0];
textarea.setAttribute("maxlength", "10");
</script>

For part1 I the inspector says: “Uncaught TypeError: textfields[i].setAttribute is not a function” , but nevertheless working without part 2.

Could you please take a look and tell me the issue?

Thank you!

Hey I think you miss aim of i;
change your code to ;
for (let i = 0; i < textfeilds.lenght; i++){ }
I think this should be work

1 Like

Oh my god, thank you soooo much! :blush:
I guess the “for ( i in array)” is not usable for interation, the i is not holding a position in the array for further processing.
Now it works, great!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.