0

I can't seem to get the input value for "name", I have tried using .value in JS but when I run the code I get undefined.

HTML code

<div class="col-1">
<label for="fname">Name</label>
</div>
<div class="col-2">
<input type="text" id="fname"  placeholder="Enter name"  required>
</div>

<div class="col-3">
<button  onClick="gather()" id="submitButton">submit</button>
</div

JS code

var submit = document.getElementById("submitButton");
submit.addEventListener("click",gather);

function gather(){
  name = document.getElementById("fname");
  message = "Thank you for subscribing "+name.value+ "!";
  alert(message);
}
Ronald
  • 17
  • 4

3 Answers3

2

Just use var for create variable and all work.

var submit = document.getElementById("submitButton");
submit.addEventListener("click",gather);
function gather(){
  var name = document.getElementById("fname");
  var message = "Thank you for subscribing "+name.value+ "!";
  alert(message);
}
<div class="col-1">
  <label for="fname">Name</label>
</div>
<div class="col-2">
  <input type="text" id="fname"  placeholder="Enter name"  required>
</div>
<div class="col-3">
  <button  onClick="gather()" id="submitButton">submit</button>
</div>

I suggest you to see this post:

Is var necessary when declaring Javascript variables?

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
1

you can simply do .value in the same line and get the value of the element

name = document.getElementById("fname").value;
console.log(name)
0

You must put all your codes into window.onload. This method running your code when all elements in page loaded. And this will solve your problem.

window.onload = () => {
//some js codes
}