I write a js code to determine which number is bigger but the result is not perfect! when I input two number with same digit numbers, the result is correct. For example when I input “2” and “3” the result is “3” but when I input “2” in first field and “55” in the second field, the result is “2”.
Thank you in advance.
sorry for my weak English.
function biggerOne() { var x = document.getElementById("firstNumber").value; var y = document.getElementById("secondNumber").value; if (x>y){ document.getElementById("Result").innerHTML=x; } else { document.getElementById("Result").innerHTML=y; } }
<!DOCTYPE html> <head> <script src="show bigger.js"></script> </head> <body> <p>insert first number</p> <input type="number" id="firstNumber" ر> <p> insert second number</p> <input type="number" id="secondNumber"> <button onclick="biggerOne()"> result </button> <!---it is so important to insert value in the below code line--> <p id="Result" value=""></p> </body>
Advertisement
Answer
Document.getElementById() returns “String” type value and comparison between two string will act differently. Better convert those string types to integer.
var x = document.getElementById("firstNumber").value; var y = document.getElementById("secondNumber").value; if (parseInt(x) > parseInt(y)) { document.getElementById("Result").innerHTML=x; } else { document.getElementById("Result").innerHTML=y; }