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.

3
  • 1
    A quick solution is to change $('#display').val() to eval($('#display').val()). Although Eval can be dangerous. Make sure you read about it and understand it. Commented Jun 22, 2015 at 4:36
  • 1
    why didn't you ask at Stack Overflow? meta.stackexchange.com/a/129632/165773 Commented Jun 22, 2015 at 5:53
  • cos i cant ask there thanks to some pple who go around down-rating question for no good reason Commented Jun 22, 2015 at 6:01

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.