简体   繁体   中英

Does not capture the second form attribute name with getAttribute('name');

I'm just looking at the JavaScript events for a project, but there is something I cannot find the reason why it does not work or does not show the event with getAttribute('name') when supposedly if there is the second like this:

<form name='otherRegistration'>
    <input type="email"></input> 
    <button class="btn btn-safe col-xs-6"></button>
</form>

<form name='registration'>
    <button class="btn btn-security col-xs-6"></button>
</form>

The question is that if it catches the name attribute of the first form name otherRegistration but does not capture the name of the second form registration which is weird and I don't have an idea why this happens, I have checked carefully and can not find the reason.

Once having the attribute name of the form does not enter the if which I do not understand because, if it revises with typeof and returns string

I would appreciate if you help me understand why and what is the solution, here the code:

function userSessionSubmit() {

    var form = document.querySelector('form');
    var formName = '';

    form.addEventListener('click', function () {
        formName = form.getAttribute('name');

        console.log(formName);

        switch (formName) {
            case 'otherRegistration':
                alert('TRIGGER OTHER'); //works 
                break;
            case 'registration':
                alert('TRIGGER REGIS'); //does not work...
                break;
            default:
                alert('nothing');
                break;
        }
    });
};

userSessionSubmit();

document.querySelector(selector) selects one element - the first one found on the page.

To select multiple elements with one query you should use document.querySelectorAll(selector) and assign it to a variable.

Example code:

const forms = document.querySelectorAll('form'); // select all forms on the page
Array.prototype.forEach.call(forms, (form) => {
   form.addEventListener('click', listenerFunc); // add on click listener to every form
}); // iterate trough found elements

Edit:

You should consider using unanonymous functions in your listeners - you can not use removeEventListener() on anonymous functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM