I'm using input text field to input numbers only. I can't use input type="number" because i probably use the decimal or (.) characters
example of expected result *whole numbers *numbers with decimal *restricted alphabets
if possible, only decimal character are allowed, the rest will restricted also in special character.
thanks for the help :>
CodePudding user response:
HTML: in the attribute step , you can define your steps like .01.
<input type="number" required name="price" min="0" value="0" step="any">
Jqery: In case you are looking for a regex that allows only numbers with an optional 2 decimal places
HTML:
<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />
JS / JQuery:
$(document).on('keydown', 'input[pattern]', function(e){
var input = $(this);
var oldVal = input.val();
var regex = new RegExp(input.attr('pattern'), 'g');
setTimeout(function(){
var newVal = input.val();
if(!regex.test(newVal)){
input.val(oldVal);
}
}, 1);
});
CodePudding user response:
using jquery validation is easily possible for input
Enter Input try it. <br/>
<input type="text" onkeypress="return event.charCode >= 46 && event.charCode <= 57" onpaste="return false">
CodePudding user response:
Here you go. Regex check for input, allow only numeric value and decimal. And if condition check, it's only take one decimal.
Example:
$(".decimal").on("input", function(evt) {
var txt = $(this).val();
txt = txt.replace(/[^0-9\.]/g, '');
if (txt.split('.').length > 2)
txt = txt.replace(/\. $/, "");
$(this).val(txt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="numeric" class='decimal'>