I know that you can use <input type="number">
to restrict a text box to integer only input. However, I was wondering if there is a possibility of range restricting this as well? The limiting factor being without using a javascript function to check it on every keyup
. That seems a little heavy and unnecessary. I would think HTML5 would have something built in to take care of this edge-case, but I haven't been able to find anything.
For example, I have an input box for a deduplication ratio where I want to restrict the user to inputting numbers (integer or float) between 3 and 7.
I have a option-select dropdown currently with whole and half numbers, but this does not provide the level of detail I'm looking for.
To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field.
By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.
_%+-]+@[a-z0-9. -]+\. [a-z]{2,3}$"> will restrict the allowed characters according that RegExp pattern (in this case: valid-looking email addresses). The title attribute will be used as a warning / notification when the user tries to submit the data not matching the requirement.
As I mentioned in the comments earlier... there isn't anything that is HTML only here (you'd think there should be). But... since you did include Javascript and jQuery in your question, I'll propose this simple and light solution.
Assuming this HTML...
<form>
<input type="number" min="3" max="7" step="0.5"></input>
</form>
Then we can use this script to handle our requirements.
$( document ).ready(function() {
$('input').change(function() {
var n = $('input').val();
if (n < 3)
$('input').val(3);
if (n > 7)
$('input').val(7);
});
});
Basically, after the change event fires, we do a quick check to make sure the values are within the guidelines, and if not, force them back within range.
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