Reputation: 716
I try to get a boolean return from a simple condition. it is possible to use Eval function to do that or may I have to use a if statement ?
here is my expression :
alert(eval($("#val1").val() + $("#val2").val() == $("#result1").val()));
It's numeric values like 1 + 1 = 2 // true
Upvotes: 0
Views: 301
Reputation: 1855
You should convert them to numbers like this:
alert(Number($("#val1").val()) + Number($("#val2").val()) == Number($("#result1").val()));
if you don't convert them to numbers,java-script assumes they are strings and does a concatenation, and then val1(1) + val2(1) = 11
$("#btn").click(function(){
console.log("Converted To Numbers: " + $("#val1").val() + " + " + $("#val2").val() + " = " + (Number($("#val1").val()) + Number($("#val2").val())));
alert(Number($("#val1").val()) + Number($("#val2").val()) == Number($("#result1").val()) );
});
$("#btn2").click(function(){
console.log("No Conversion: " + $("#val1").val() + " + " + $("#val2").val() + " = " + $("#val1").val() + $("#val2").val());
alert($("#val1").val() + $("#val2").val() == $("#result1").val() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="val1">
<input type="text" id="val2">
<input type="text" id="result1">
<br>
<input type="button" id="btn" value="Convert To Numbers">
<input type="button" id="btn2" value="No Conversion">
Upvotes: 4