I have a text input
which I want to limit to only numbers. No other characters. I also want to limit from 0 - 255.
If a an 'illegal' char, or amount is entered, I want it to wait a second then delete that character or number. I was so far able to get the illegal characters.
Here's what I want to do:
- Make it wait a second, then delete it.
- Limit number from 0 - 255.
If more than 255 gets entered, I just want the last digit to wait, then delete itself. Just like the 'illegal' chars.
I already got the illegal character implemented. Here's the code:
JSFiddle
$('input[name="number"]').keyup(function(e) {
if (/\D/g.test(this.value)) {
// Filter non-digits from input value.
this.value = this.value.replace(/\D/g, '');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number" />
Try using if
condition to check if this.value
is greater than 255
, if true , set this.value
to first two characters of input using String.prototype.slice()
How about making it wait a second?
Try using setTimeout()
function disableInput(el) {
// create array of checks on `el.value`
var checks = [/\D/g.test(el.value), el.value > 255];
// if `el.value` contains non-digit character,
// or is greater than 255 ;
// `Array.prototype.some()` checks for `true` value
// if either `checks[0]`, or `checks[1]` is `true` do stuff
// else set `el.value` to user input
if (checks.some(Boolean)) {
// disable input
$(el).prop("disabled", true)
// delay 1 second
setTimeout(function() {
if (checks[0]) {
// Filter non-digits from input value.
el.value = el.value.replace(/\D/g, '');
}
// if `this.value` greater than 255 , set `this.value` to
// first two characters of input
if (checks[1]) {
el.value = el.value.slice(0, 2);
};
$(el).prop("disabled", false).val(el.value).focus()
}, 1000)
}
}
$('input[name="number"]').keyup(function(e) {
disableInput(this)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number" />