I have a number input text box and I want to allow the user to edit but do not want to allow the user to enter any other text except numbers. I want them only to be able to use the arrows on the number input box.
<input type = "number" min="0" max="10" step="0.5" input id="rating" name = "rating" class = "login-input" placeholder = "Rating 1-5:" value="0">
You can achieve this by pure
JavaScript
. Create this function that you can reuse in your script.You may preferably call this
onkeypress
event handler.However, I would recommend the unobtrusive style of writing JS using because it is good to keep the HTML semantic and away from pollution. You can execute the function on event handler that we would attach to this text box using vanilla JavaScript or jQuery.
To restrict every character you can just simply use
e.preventDefault()
.Besides, you can also use
return false
instead butpreventDefault()
is better in this case andreturn false
should be chosen wisely. It is good to know the difference between both of them.document.getElementById('rating').onkeypress = function() { return false; }
This will prevent the default behavior of keypresses on that element i.e. text showing up.