0

i have a drop down list in my html with values show here,

<select id="thedropdown">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>

And my javascript:

function myFunction()
{
var a = document.getElementById("thedropdown");
var b = a.options[a.selectedIndex].value;

var y=b;
var x=y+2;
var demoP=document.getElementById("demo")
demoP.innerHTML= x;
}

However the answer when i click the button makes it 22 when it should be 4. you can see my problem. Cheers for help in advance

user2057440
  • 1
  • 1
  • 1
  • 3

5 Answers5

6

Right now your code concatenates strings. You need to parseInt() or parseFloat() (or Number() or +) the values before adding.

When using parseInt() make sure to always specify the second argument (the radix):

b = parseInt(a.options[a.selectedIndex].value, 10);
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
3

You can use unary + to convert numeric string to a number:

var y=+b;

or

var x=+y+b;
Plynx
  • 11,341
  • 3
  • 32
  • 33
2

You are concatenating a string instead of adding numbers:

var x=y+2;

Try that:

var x=parseInt(y)+2;
mika
  • 1,411
  • 1
  • 12
  • 23
0

You have to convert your values with parseInt function:

    var y = parseInt(b, 10) + 2;
Mickael
  • 5,711
  • 2
  • 26
  • 22
0

If one of the operands is a string , + operator performs concatenation.

this will work

function myFunction()
{
  var a = document.getElementById("thedropdown");
  var b = a.options[a.selectedIndex].value;

  var y=b;
  var x= parseInt(y) + 2;
  var demoP=document.getElementById("demo")
  demoP.innerHTML= x;
}

Note var x= parseInt(y) + 2;

Tapan Nallan
  • 1,762
  • 3
  • 17
  • 37