I have trouble restricting the input characters to integers only. Is there a way by which I can restrict the decimal numbers or float from being entered into the input type="number
"?
I have also tried the following approach by replacing .
with ''
whenever event for keyup
is fired:
$("#myForm").on('submit', function(e) {
e.preventDefault();
});
$("#number").on('keyup', function() {
var regex = new RegExp(/\d+\.\d?/g);
var number = $(this).val();
if (regex.test(number)) {
number = number.replace(/\./g, '');
$(this).val(number);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm" action="//google.de">
<p>Input type number step 1</p>
<input type="number" name="number" id="number" step="1" min="0"/>
<input type="submit" />
</form>
With the above code, following are the case results:
WORKS:
2.3
FAILS:
2..3
2….3
2.3.3.3.3.3.3.3.3.3.3.333...3
I need only 2 (any integer) to be allowed, and from all other cases (including the copy and paste), the decimal should be removed.
So my final question is that how can I restrict float numbers from being entered in the input field with type="number"
? If that's not possible then how can I change the above code to meet my requirements?
EDIT:
Please do not close this question if this question partially matches another. I have written a code here too. I want to know, what's wrong with it.