-3

I'm trying to read the value from a textbox and it returns nothing.

Within the console, it simply shows a white line, with the line number of the console.log statement.

var amount = document.getElementById("billAmt").value;
document.getElementById('calculate').addEventListener('click', function() {
  console.log(amount);
});
<input id="billamt" type="text" placeholder="Bill Amount">
<button type="button" id="calculate">Calculate!</button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 5
    `amount` does not magically update. Put your `var` inside your event handler, where you actually want to use it. – Niet the Dark Absol Aug 27 '18 at 11:55
  • _This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting_ – mplungjan Aug 27 '18 at 11:58
  • Welcome to SO. Feel free to delete the question since it is not really useful to anyone but you – mplungjan Aug 27 '18 at 11:58
  • @mpl This is more than a typo in `billamt`. – deceze Aug 27 '18 at 12:01
  • @deceze I can likely find a dupe if you want – mplungjan Aug 27 '18 at 12:08
  • @mpl Be my guest. – deceze Aug 27 '18 at 12:10
  • 1. https://stackoverflow.com/questions/20500434/why-wont-this-simple-event-listener-work-in-javascript – mplungjan Aug 27 '18 at 12:11
  • Alternative: https://stackoverflow.com/questions/1759987/listening-for-variable-changes-in-javascript – mplungjan Aug 27 '18 at 12:16

1 Answers1

0

There are couple of issues in your code:

  1. Typo in billamt. It should be billAmt in HTML or change either of them to make same
  2. You need to get the value inside the click function.

document.getElementById('calculate').addEventListener('click', function() {
  var amount = document.getElementById("billAmt").value;
  console.log(amount);

});
<input id="billAmt" type="text" placeholder="Bill Amount">
<button type="button" id="calculate">Calculate!</button>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62