Reputation: 221
I'm trying to restrict 0 as first digit in input field. It works fine in macbook, but when user enter the amount in windows system the input field excepts the digit 0 and it is also not excepting the digit 9 as first digit, for eg: 9845 but it excepting like 8945. Below is the code.
I am just getting confused as where the bug is. It would be great if anyone can help me out with this:
JS CODE:
$("#stamp_amount").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
if ( event.keyCode == 46 || event.keyCode == 8) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode !==9) && (event.keyCode < 48 || event.keyCode > 57 )) {
event.preventDefault();
}
else{
if($.trim($(this).val()) =='')
{
if(event.keyCode == 48 || event.keyCode == 57 || event.keyCode == 96 || event.keyCode == 105){
event.preventDefault();
}
}
}
}
});
Upvotes: 0
Views: 52
Reputation: 43479
Instead of checking what key was pressed check input value itself.
Regex /^0|[^0-9.]/
means starts with 0 or contains character other than numbers and .
$(document).ready(function() {
$('#inp').change(function() {
if ($(this).val().length == 0 || /^0|[^0-9.]/.test($(this).val())) {
$('#valid').removeClass('valid');
} else {
$('#valid').addClass('valid');
}
// make input valid
$(this).val($(this).val().replace(/^0+|[^0-9.]+/, ''));
});
})
#valid:after {
content: "No";
color: red;
font-weight: bold;
}
#valid.valid:after {
content: "Yes";
color: green;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inp" placeholder="51.54" />Eur
<br/>
<span id="valid"></span>
Upvotes: 1