0

Why do I get a empty string "" when I try to get the value of my input field instead of the number I gave.When I type billAmount in the console window,I get "" returned.Why is that?

var billAmount = document.getElementById('bill-id').value;
<html>
<input type="number" id = "bill-id" class="bill-input" placeholder="0">
</html>

2
  • When do you try to get the value? If your code runs before you put your value in the input field it wont have your value, and variables do not auto update Commented Jul 30, 2021 at 21:11
  • placeholder is not a value use value="0" to get value, Also put js below html if possible Commented Jul 30, 2021 at 21:11

2 Answers 2

2

Your code only executes once.

If you want to update the variable everytime the user changes the value of the input, listen for the input event:

var billAmount;
document.getElementById("bill-id").addEventListener('input', function(){
  billAmount = this.value;
  console.log(billAmount);
})
<html>
<input type="number" id = "bill-id" class="bill-input" placeholder="0">
</html>

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

Comments

2

First, your webpage loads the input element in the DOM. Then, the javascripts starts running. It rapidly collects the input's value which is empty. Presuming the only line of JS is var billAmount = document.getElementById('bill-id').value;, it finishes its jobs. Your JS doesn't detect any change of the input's value. You should add an event listener and change the variable each time you enter something.

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.