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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
change type of x and y to number and then try to compare.for convert you can use Number or parsint
if (Number(x) > Number(Y))
//some code
else
//some code
CodePudding user response:
<!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>
<script>
function biggerOne() {
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;
}
}
</script>
</body>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Use the parseInt method.
CodePudding user response:
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;
}