user1238097
user1238097

Reputation: 87

can't figure addEventListener error when script is in body

I am working on a submit button using an addEventListner to a form, but I am stuck with the addEventlister of undefined error. I tested if the element is true and it returns true.

This is my form:

<form action="POST">
    <input name="name" type="text" autocomplete="given-name">
    <input name="lastname" type="text" autocomplete="given-name">
    <button type="button" id="for_input">Submit</button>
</form>

This my java script:

//Check if the element exists.
var el = document.getElementsByName('for_input');
        if(el) //check if true
            console.log("Value is true"); 
        else
            console.log("Value is false");

//define alert to check click        
var showMe = function(){alert("clicked worked");}; 


el[0].addEventListener("click", showMe,false);

The error:

Uncaught TypeError: Cannot read property 'addEventListener' of undefined

I tried adding to the of the html body but still receiving the same error.

Upvotes: 0

Views: 89

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118289

You don't have any element name of for_input, but you have a button with an ID of for_input. So use querySelector or getElementById method instead of getElementsByName method on document.

var el = document.querySelector('#for_input');
if (el) //check if true
  console.log("Value is true");
else
  console.log("Value is false");

//define alert to check click        
var showMe = function () { alert("clicked worked"); };


el.addEventListener("click", showMe, false);

document.getElementsByName('for_input') returns NodeList [], which was assigned to el, as there is no html element of name="for_input" found in the document object. Later when you called el[0] it gave you undefined because el has an empty node list. So undefined.addEventListener(..) call caused the error you see in the log.

Upvotes: 2

ATUL DIVEDI
ATUL DIVEDI

Reputation: 156

You are missing element with name for_input, its button id, So use getElementById

var el = document.getElementById('for_input');

Now el is not an array, so no need to add array position like el[0] just use el

el.addEventListener("click", showMe, false);

Upvotes: 1

vladwoguer
vladwoguer

Reputation: 978

You forgot to add the name, you are using id="for_input" instead of name="for_input".

<button type="button" name="for_input">Submit</button>

Upvotes: 1

Related Questions