0

i have the following Html

<input class="top-display" value="5+5" id="display" disabled="disabled"> </input>
<button class="btn" > submit </button>

And jquery

$('.btn').click(function(){
    var selected = $('#display').val();
    alert(selected);

});

fiddle Here my focus for this code is letting jquery to automatically do the math for me. like instead of jquery alerting "5+5" it should alert "10". and if the value = "5-5" is should alert "0"; without adding any if statement.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Ghostff
  • 1,407
  • 3
  • 18
  • 30
  • 1
    A quick solution is to change `$('#display').val()` to `eval($('#display').val())`. Although [Eval can be dangerous](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval). Make sure you read about it and understand it. – Rowan Freeman Jun 22 '15 at 04:36
  • 1
    why didn't you ask at Stack Overflow? http://meta.stackexchange.com/a/129632/165773 – gnat Jun 22 '15 at 05:53
  • cos i cant ask there thanks to some pple who go around down-rating question for no good reason – Ghostff Jun 22 '15 at 06:01

4 Answers4

2

You can use eval()

The eval() method evaluates JavaScript code represented as a string.

Change your code to this:

$('.btn').click(function(){
    var selected = eval($('#display').val());
    alert(selected);
});

Also note:

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller.

Read more at MDN to understand the risks involving eval.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Community
  • 1
  • 1
Rowan Freeman
  • 15,724
  • 11
  • 69
  • 100
2

Updated Fiddle

$('.btn').click(function(){
    var selected = $('#display').val();
    alert(eval(selected));
});

Don't forget to add proper error handling to avoid errors in the situations where there are in compatible values.

Edit: The eval function has known security vulnerabilities. It is always advisable not to use it.

$('.btn').click(function(){
    var selected = $('#display').val();
    alert(evil(selected));
});

function evil(fn) {
    return new Function('return ' + fn)();
}

This is another solution I found in another thread.

Community
  • 1
  • 1
rrk
  • 15,677
  • 4
  • 29
  • 45
1

Reason why you are getting 5+5 in alert is because your 'expression' is not executed. Where eval(args) will execute the arguments.

street hawk
  • 565
  • 7
  • 12
1

eval() can be used in this case as long as you sanitize the input string like below:

$('.btn').click(function(){
    // strip anything other than digits, (), -+/* and .
    var selected = $('#display').val().replace(/[^-()\d/*+.]/g, '');
    alert(eval(selected ));
});

You can also refer to this thread for other alternatives to eval(). The security risks of using eval() has been discussed here in great detail.

Cheers!

EDIT: Updated fiddle link here for testing.

Community
  • 1
  • 1
DMv2
  • 198
  • 1
  • 12