So I have lets say N textarea elements in my webpage and I want to get the value of the textarea whenever user tries to type something into that. I wrote the code
<textarea rows="10" cols="25">
</textarea>
<textarea rows="10" cols="25">
</textarea>
<textarea rows="10" cols="25">
</textarea>
and the script is
document.addEventListener('DOMContentLoaded', function (){
var textareas = document.getElementsByTagName("textarea");
console.log(textareas.length);
for(var i = 0; i<textareas.length; i++){
textareas[i].onkeypress = function (){
console.log(textareas[i].value);
}
}
});
the line console.log(textareas.length);
is printing the value 3 but I don't understand why console.log(textareas[i].value);
is throwing error
Uncaught TypeError: Cannot read property 'value' of undefined
I mean if textareas[i]
is not defined for it then why textareas[i].onkeypress
is working properly. If it is the wrong way how can I get the value of the respective textarea when user writes something on it.