IronMocha IronMocha - 1 month ago 8
Javascript Question

JS Outputting a form value receives 'undefined' in console

I am trying to create a form that when submitted will just output the two values to the console. However, when I run it, only the email field is being displayed and the name field is just showing 'undefined'.

I have created a JSFiddle of what I have so far.

https://jsfiddle.net/hbzxcvjj/1/

JS:

var name = document.getElementById("name");
var email = document.getElementById("email");
var submitButton = document.getElementById("btn-signup");

var sendInfo = function(){
console.log(name.value);
console.log(email.value);
}
submitButton.onclick = sendInfo;

Answer

try moving your variable definitions into the function, this is how it should look:

var submitButton = document.getElementById("btn-signup"); 

var sendInfo = function(){
var name = document.getElementById("name");
var email = document.getElementById("email");
console.log(name.value);
console.log(email.value);
}
submitButton.onclick = sendInfo;