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

3
  • Probably because b is a string, and thence y, and thence you are converting the number 2 to a string and tacking it on the end of the first "2" string Commented Feb 9, 2013 at 16:51
  • Fiddle: jsfiddle.net/L3zbc uses parseInt() Commented Feb 9, 2013 at 17:00
  • check out Javascript unary + operator x = +y + 2; Commented Jan 26, 2015 at 23:28

5 Answers 5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

so do i have to create a new var for that like var c = parseInt(b)?
That would work, as would b = parseInt(b).
3

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

var y=+b;

or

var x=+y+b;

Comments

2

You are concatenating a string instead of adding numbers:

var x=y+2;

Try that:

var x=parseInt(y)+2;

Comments

0

You have to convert your values with parseInt function:

    var y = parseInt(b, 10) + 2;

Comments

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.