-2

I have several text fields, and the value of these fields can be "4", "-2", "10", etc.

I would like to retrieve this value and make the corresponding mathematical operation:

var price = 50;
var value = $ ( "# myTextField").val(); //e.g value = "+50"
var finalprice = price + value

alert(finalprice)

But, of course it doesnt work and only display "50+50". Could you please help me so it can also work if my value was -30 ? Thanks a lot

EDIT: Sorry but you didn't understand me: I need to keep the math operator of my text field (- or +) so I can't convert my string into an Integer.

Yoyo
  • 21
  • 5

2 Answers2

2

you need to parse string to an integer:

var value = parseInt($("#myTextField").val(), 10);
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
0

You should parse the string as integer - parseInt() https://jsfiddle.net/wk4a5vm2/1/

If you want to get string with an operator you should use eval() https://jsfiddle.net/wk4a5vm2/4/

Adrian C.
  • 260
  • 5
  • 21