3

I am collecting a text area value(number in decimal ) using its id to a javascript variable, adding another variable value (number in decimal), and displaying the result in same html page

text area code:

<div class="input-resp"><span><input  class="textbox" id="num" name="count" type="text" size="5" maxlength="3"  value="" /></span></div>

passing value to var and adding it to another var

var a = document.getElementById('num').value;
var b = 1000;
var c = parseFloat(a) + parseFloat(b); 

passing var c to div id test

document.getElementById("test").innerHTML = c;

html for test id

<div id="test"></div>

But here, whenever I am updating the text area with new number, the final output is not updating instantly.I have refresh the page manually to get new value. Is there anyway I update the value without a page refresh ?

putvande
  • 15,068
  • 3
  • 34
  • 50
acr
  • 1,674
  • 11
  • 45
  • 77
  • Where is your jQuery and where did you define the variable `data`? And further more.. how are you doing this? With a click event? – putvande Jul 27 '13 at 17:05
  • @putvande : 'data' was a typo.variables are a,b and c.there is no click,iwould like to update the value whenever I type in textarea – acr Jul 27 '13 at 17:10

1 Answers1

3

If it's going to update whenever you type into the input, you need an event handler:

document.getElementById('num').onkeyup = function() {
    var a = 1000 + parseFloat(this.value);
    document.getElementById("test").innerHTML = a || 0;
}

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    Note that there is no need to `parseFloat` the `1000` number. Also note that this does not work on paste or any other inputs than keyboard, use appropriate event for your needs (the `input` event comes to mind). – David Hellsing Jul 27 '13 at 17:11
  • @David - the [input event](https://developer.mozilla.org/en-US/docs/Web/Reference/Events/input) is not really widely supported – adeneo Jul 27 '13 at 17:13
  • agreed, but there are other ways to simulate it for older browsers, f.ex using `setInterval`. I’m just mentioning it in case the OP needs to care for pasters as well. – David Hellsing Jul 27 '13 at 17:15