javascript addEventListener firing on all elements
-
07-06-2021 - |
题
Im sure I have missed something obvious but any idea why the following addEventListener code is firing everywhere (on not just on the submit button)?
HTML:
<form action="#">
<input type="text"><br>
<input type="text"><br>
<button id="submit">submit</button><br>
</form>
JS:
function validate () {
var inputs = document.getElementsByTagName('input');
var inputs_length = inputs.length-1;
for (i=0; i<=inputs_length; i++) {
var inputs_value = document.getElementsByTagName('input')[i].value;
if (inputs_value == "") {
alert('there is a text box empty');
}
}
}
var el = document.getElementById('submit');
if (el.addEventListener) {
el = addEventListener('click', validate, false);
} else if (el.attachEvent) {
el.attachEvent('onclick', validate);
}
THE FIX IS CHANGE
el = addEventListener('click', validate, false);
TO
el.addEventListener('click', validate, false);
MY TYPO :(
解决方案
Change this:
if (el.addEventListener) {
el = addEventListener('click', validate, false);
To this:
if (el.addEventListener) {
el.addEventListener('click', validate, false);
其他提示
A lengthy comment.
In your code:
// inputs is an HTMLCollection of all the inputs
var inputs = document.getElementsByTagName('input');
// No need for the -1
var inputs_length = inputs.length;
// Don't forget to declare counters too, very important
// Just use < length
for (var i=0; i<inputs_length; i++) {
// Instead of this very inefficient method
var inputs_value = document.getElementsByTagName('input')[i].value;
// use the collection you already have
var inputs_value = inputs[i].value;
if (inputs_value == "") {
alert('there is a text box empty');
}
}
Also better to declare inputs_value
at the beginning so all declarations are in one place, but as you have it is not harmful.
Oh, and don't give a form element a name or id of "submit" (or any other form method) as it will shadow the form method of the same name so it can't be called.
不隶属于 StackOverflow