I've got a HTML number input element: <input type="number">
.
Problem is that I can also input following characters: + - e E , .
which I don't want the user to be able to write.
How do I restrict these?
Edit: Boris K has got an even better answer.
Original answer:
This would be a way to accomplish that:
var ageInput = document.getElementById("age")
ageInput.addEventListener("keydown", function(e) {
// prevent: "e", "=", ",", "-", "."
if ([69, 187, 188, 189, 190].includes(e.keyCode)) {
e.preventDefault();
}
})
<input type="number" id="age">
You shouldn't rely only on <input type="number">
, because that would work only in moderns browsers with different behaviours depending on the browser.
Use jQuery to perform additional checks (with a regexp):
$('#my-input').keypress(function() {
var inputValue = $(this).val();
var reg = /^\d+$/;
if (reg.test(inputValue)){
alert("input value is integer");
} else {
alert("input value is not an integer");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With