So I have a function that fires when a user enters in 5 characters in an input field.
However, whenever I place additional characters after the 5 has been fulfilled it keeps on firing the event.
How do I prevent this from occurring?
$(function(){
var $zipEntry = $('#zipEntry').bind('keyup',function(event) { //bind to key up, doesn't require
//make sure that there are 5 numbers... or length = 5 since numeric only input
var $this = $(this); // cache $(this)
if ($this.val().length == 5){ // use cached
console.log("There are 5 characters!!");
$this.trigger('zipEntered');
}
});
If i understand you correctly, you need use "greater or equal" instead "equal"
if ($this.val().length >= 5){
Also, why do you use $ in variable names??
Try unbinding the event after you're done listening for it.
if ($this.val().length == 5){
console.log("There are 5 characters!!");
$this.trigger('zipEntered');
$('#zipEntry').unbind('keyup');
}
Can't the problem be corrected at the source? Put a maxlength on the input field?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.