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);
}
2
  • Did you try giving the input an empty value parameter? value="" Commented Mar 23, 2021 at 9:24
  • weird, your code looks correct. what does it say when you log just the input element (name)? Commented Mar 23, 2021 at 9:26

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.