leojarina
leojarina

Reputation: 157

Adding Value in a textfield

I have one input text where the value is "5+3" I believe this is a plain string, is there anyway to parse it as (8) in a alert() function? 5 + 3 is a value of one textbox and its not separated by another textbox. Is there any javascript function can handle this?

Upvotes: 1

Views: 68

Answers (2)

Paul
Paul

Reputation: 12440

eval() can execute strings as JavaScript statements:

<input type="text" id="addNums" />
var addNumsInput = document.getElementById('addNums'),
    val = addNumsInput.value;

alert(eval(val));

Fiddle: http://jsfiddle.net/LAwm3/

Just for your reference, eval is evil https://www.google.com/#hl=en&sugexp=les%3B&gs_nf=1&tok=WiRGhtSngs9KeYHImoAsFQ&cp=6&gs_id=3e&xhr=t&q=eval+is+evil&pf=p&output=search&sclient=psy-ab&oq=eval+i&gs_l=&pbx=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&fp=2aae9199cf6ab275&biw=1920&bih=989

Upvotes: 1

jeff
jeff

Reputation: 8348

You can use eval():

alert(eval("5+3")); // alerts 8

Upvotes: 1

Related Questions