I have a HTML input field, lets say
<input type="text" maxlength="50" size="50" name="subject" id="subject">
I need to trigger a function on every 3 charachters entered.
For example:
If user enters "aaa" - trigger an event, the he continues to enter "aaa bbb" - trigger event again, etc.
But spaces should not be counted.
I need this to post value of the field to external API - to do searching.
Has anybody done this before?
Please help.
try something like this. Bind an event handler to input
on page load
$(function(){
$("#subject").change(function(){
var val = $(this).val().trim();
val = val.replace(/\s+/g, '');
if(val.length % 3 == 0) { //for checking 3 characters
//your logic here
}
});
});
If you want to actually do this in real-time while the user is typing and not require them to remove focus from the input, you can use a keyup
event and slightly modified logic to filter out spacebar presses.
$('#subject').on('keyup', function(e) {
if (e.which !== 32) {
var value = $(this).val();
var noWhitespaceValue = value.replace(/\s+/g, '');
var noWhitespaceCount = noWhitespaceValue.length;
if (noWhitespaceCount % 3 === 0) {
// Call API
}
}
});
jsfiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With