0
What is the problem with this code???
9 Answers
+ 10
1) Give input name different from your function.
<input type="button" name="compar" onclick="compare()"/>
2) getElementById takes strings.
3) Inside if condition you need to compare numbers not strings that's why used eval.
function compare()
{
var num1=document.getElementById('num1').value;
var num2=document.getElementById('num2').value;
if(eval(num1)>eval(num2))
{
alert("First no. is greater...");
}
else
{
alert("Second no. is greater...");
}
}
+ 8
@Ashwani Kumar:
You should avoid use of eval() function for cast string to number... better way is to use the Number() contructor:
var s = '42';
var n = Number(s);
<< eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.
eval()Â is also generally slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.
There are safer (and faster!) alternatives to eval() for common use-cases. >>
source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
+ 6
@vishp Thanks for the information. âșïž
@Sandip You can replace eval() with Number() as mentioned by @vishp following the security standards and good practices of JS code.
+ 6
@Sandip You missed the trick in these two lines
var num1=document.getElementById('num1').value;
var num2=document.getElementById('num2').value;
+ 2
thanks its working....
earlier i forgot the quotation marks.
+ 1
Thanks...Its working fine.
+ 1
yeah! done.
+ 1
it gives error on line number 11.
0
Problem!!!
Not showing output:
https://code.sololearn.com/WrqF91f4dzaY/?ref=app