Reputation: 79
Is it possible to restrict a form field in HTML with Jquery/Javascript to only 3 decimals . What I mean is that: 33.334 should be allowed as input 3.344 & 444444.556 etc. as well but it should not allow 5.6664 etc.
How can I do that?
Upvotes: 1
Views: 240
Reputation: 59292
You don't need jQuery to do that. Just use pattern
attribute of <input>
like this
<input type="text" pattern="^\d+\.\d{0,3}$">
The above would work on most browsers but if you want to support some old browsers, you would bind that <input>
on a key-based event and check for the value using the above regex and restricting the user input.
$('input').on('blur', function () {
if (!/^\d+\.\d{0,3}$/.test($(this).val())) {
alert("Must be a number upto 3 decimals!");
}
});
Press Enter to see pattern
in action. Click elsewhere to see jQuery in action
Upvotes: 2