Search code examples
javascriptjqueryhtmlcssgetelementbyid

Javascript: Clicking a button inside a div/form not executing the javascript meant for it?


Okay, so I have a button inside a div. Here is that bit of HTML:

<div class="row">
    <button type="button" id="submit">Send</button>
</div>

Before this button, there are other fields like name and email and stuff, and those are all inside a form, with the id "contactForm" (which is inside a div with class name "container").

I am making a JS file. I am trying to get it so that when the user puts in all the info like name & stuff, and hits submit, it will console.log() the name. That JS portion looks like this:

// Listen for submit btn click
document.getElementById('contactForm').addEventListener('submit', submitForm);

function submitForm(e) {
    e.preventDefault();

    var name = document.getElementById('name').value;
    var email = document.getElementById('email').value;
    var message = document.getElementById('message').value;

    console.log(name);
};

Right, so this part looks fine to me, but then when I go into the localhost where the website is, and i put in whatever random stuff into the name, email and message fields, and i hit submit, nothing happens.

The debugger/console says

Uncaught TypeError: Cannot read property 'addEventListener' of null

On line 48, which is this:

document.getElementById('contactForm').addEventListener('submit', submitForm);

I started learning js today, so pretty new, but i cant find anything online that solves this problem. I found some that suggested i put the big JS portion inside a document.ready function, so it runs after everythings loaded. If I do that, which I tried, there is no error (like the line 48 one). It just doesnt say anything, and clicking on the btn doesnt do anything either (as in, doesnt show the name like i wanted).

Pls help, thanks.


Solution

  • If you want to use the "Submit" event, you have to made a form which have <input type="submit">, your button with the id'submit' is not a valid submit button.

    For simple, if you want the function to be executed when your button is clicked, just use this:

    document.getElementById('submit').addEventListener("click", function(){
        e.preventDefault();
    
        var name = document.getElementById('name').value;
        var email = document.getElementById('email').value;
        var message = document.getElementById('message').value;
    
        console.log(name);
    });