A slight issue with your question is that the type of the input is text
rather than number
. You can change the type of the input by doing <input type=number id="my-input">
.
If you want to keep the type you will have to check if the input is a number.
In either case you will have to convert the value of the input from string to number since numeric operations using strings are wrong most of the time (there are rare specific cases where the outcome is the same). The only difference between using text and number is having to check if the value of the input is valid, which you can do using isNaN
after the conversion. I usually prefer forcing JavaScript to convert the text by using - 0
over parseInt
or parseFloat
, since it's scricter and will not convert "123test"
to 123
.
Here is a solution working with number
document.getElementById("my-button").addEventListener("click", function() {
if (document.getElementById("my-input").value - 0 <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
});
<input type="number" id="my-input">
<button id="my-button">Submit</button>
Here is a solution working with text
document.getElementById("my-button").addEventListener("click", function() {
var value = document.getElementById("my-input").value - 0;
if (isNaN(value)) {
alert("Not a number");
} else if (value <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
});
<input type="text" id="my-input">
<button id="my-button">Submit</button>