Reputation: 11
I need to make a text field accept only numbers and decimal point, and default to two decimal places. I got this code from a search here. It works for accepting only numbers. I need to make it accept decimal point, and default to two decimal places.
<input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" />
Thanks
Upvotes: 0
Views: 3574
Reputation: 6418
You could use a regular expression to limit what can be entered into the field.
As an example:
<input type="text" pattern="(?:[01]|2(?![4-9])){1}\d{1}:[0-5]{1}\d{1}">
You can visit a site like regexlib.com which can help you build and test the type of regex you are seeking.
There may be a better or more eloquent method, but this easy and works for me.
Upvotes: 1
Reputation: 489
If you want to always show 2 decimal places, you can reformat the input on change to round and display to 2 decimals:
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
return false;
return true;
}
$("#twodecimals").change(function() {
var format = parseFloat(Math.round($(this).val() * 100) / 100).toFixed(2);
$(this).val(format);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="twodecimals" onkeypress="return isNumberKey(event)" />
Upvotes: 0
Reputation: 2851
Leave it to HTML5:
<input type="number" step="0.01">
Also, remember about server side validation (in PHP for example). Don't try to force some missing keypress, or don't override default browser behaviour. This is not user friendly.
What will you do if you press A, and nothing is displayed? Would you go to a shop for a new keyboard?
In that case try to give the user a clue, what type of data you expect. Give the user a tool (type="number") to show best possible keyboard layout on the phone.
But don't try to do it "better". In that case it means worse.
More on the subject:
Upvotes: 0