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!