javascriptvalidationaddeventlistenerattachevent

javascript addEventListener firing on all elements


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 :(


Solution

  • Change this:

    if (el.addEventListener) {  
        el = addEventListener('click', validate, false);  
    

    To this:

    if (el.addEventListener) {  
        el.addEventListener('click', validate, false);