Guru Charan
Guru Charan

Reputation: 41

how to get value of an input box in html and do operations on it

I was testing a simple code to:

  1. Get value of an input box
  2. Do Mathematical operations on it...

My Code:

setInterval(function(){var a=document.getElementById("myInputBox").value;var b=a+1;a.value=b;},1000);    

I am trying to add 1 to the value of that input box, every 1 second.

For example, if the box has value 1 ,then after 1 second it should become 2,....and so on.....

But it gets joined with the box's value, like 11 instead of 2.

Why is that?

Upvotes: 1

Views: 108

Answers (2)

bloodyKnuckles
bloodyKnuckles

Reputation: 12089

var b = parseInt(a) + 1;

a is a string, so the + is interpreted as string concatenation by default. To fix, pass a to parseInt because it returns a type integer. Now the + becomes a math operator.

Extra Credit:

var b = parseInt(a, 10) + 1;

For an extra measure of integrity, pass the second (radix) argument, ensuring base 10 is used to determine the return integer value.

Upvotes: 2

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

Try with full code & demo:

get value from inputbox is a string, so it can't calculate mathematically. so, at first convert string to numeric by using function parseInt and then calculate and put into box.

setInterval(function() {
  var box = document.getElementById("myInputBox");
  var r = parseInt(box.value, 10) + 1;
  box.value = r;
}, 1000);
<input type="text" id="myInputBox" value="1" />

Upvotes: 2

Related Questions