jQuery live search when 4 numbers entered
-
14-03-2021 - |
Question
How do I do a live search only once the user has typed in 4 numbers into the input?
It basically needs to contact the php page using $ajax which I already have.
I thought it might be an input.length == 4
but I tried it and failed.
Solution
You can use regular expressions to check if the value of the input consists exactly of four digits.
$("#test").keyup(function() {
if(/^\d{4}$/.test($(this).val())) {
alert('please call $.ajax here');
}
});
where #test
is:
<input type="text" id="test" />
HERE is the code.
OTHER TIPS
try $('#input').val().length;
This is more of a regex problem:
if ($(this).val().replace(/[^0-9]/g,'').length >= 4) {
}
You should also prevent any keypress that doesn't pass this test:
/^[^0-9, ]$/.test($(this).val())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow