Reputation: 1171
I found many links regarding this question but none answers the problem correctly(completely). How to restrict user to allow only one decimal point in textbox. 1.3 , 5.6 etc (user cannot enter two decimals) . And also user should not be able to copy paste other invalid data to the text field.? How to achieve this in javascript or jquery??
Upvotes: 0
Views: 4403
Reputation: 392
I know this is a very late reply for this question but since there is no satisfactory answer provided here, I will share my solution for future references.
you can add this function to your javascript file which will allow only one decimal point in that specific textbox input:
function oneDecimalOnly(element) {
var charCodeEnteredEntered = (event.which) ? event.which :
(window.event.keyCode) ? window.event.keyCode : -1;
// '.' decimal point
if (charCodeEnteredEntered === 46) {
// Allow only 1 decimal point
if ((element.value) && (element.value.indexOf('.') >= 0))
return false;
else
return true;
}
return false;
}
<form>
<input type="text" name="decimal" id="decimal" onkeypress="return oneDecimalOnly(this);">
</form>
I hope this will do fine. For more information visit http://www.c-sharpcorner.com/blogs/allow-only-numeric-values-and-allow-only-one-dot-in-textbox-using-javascript1, I found it very helpful.
Upvotes: 1
Reputation: 110
I think you need this: Formance.js github: https://github.com/omarshammas/jquery.formance
Upvotes: 0
Reputation: 3328
You don't necessarily need javascript for that, use the HTML5 pattern attribute for an input:
<form>
<input type="text" required pattern="[-+]?(\d*[.])?\d+">
</form>
As soon as you try to submit the form, the browser should show an error message. In older browsers you can polyfill this non-existent functionality.
Upvotes: 2