Joel Joel Binks
Joel Joel Binks

Reputation: 1666

How to prevent BLUR event from firing multiple times?

I have certain text input fields where if users change a value and then blur away from that text field, the js will fire an ajax request to update that value in the db. The problem is that I wrote a test to get such an event to fire and I notice that the inner 'blur' event usually fires between two and five times after I tab out of the input field:

$('input[type=text]').on('input propertychange paste', function() {
    $(this).on('blur', function () {
        console.log('blur');
    });
});

Even if I turn off the blur event handler right after catching it, it still fires two or three times. How do I get this to happen only once?

Upvotes: 1

Views: 15039

Answers (2)

Cerbrus
Cerbrus

Reputation: 72857

Just keep track of a hasFired boolean:

var hasFired = false;
$('input[type=text]').on('input propertychange paste', function() {
    $(this).on('blur', function () {
        if(!hasFired){
            hasFired = true;
            console.log('blur');
        }
    });
});

Actually, the real problem here is that you're binding the blur event multiple times. You can use a boolean like above to prevent that:

var isBound = false;
$('input[type=text]').on('input propertychange paste', function() {
    if(!isBound){
        isBound = true;
        $(this).on('blur', function () {
            console.log('blur');
        });
    }
});

Upvotes: 8

Robin Carlo Catacutan
Robin Carlo Catacutan

Reputation: 13679

Another solution would be is to create a class for those elements that already bound by that event.

$('input[type=text]').on('input propertychange paste', function() {
    if(!$(this).hasClass("bound")) {
      $(this).on('blur', function () {
         $(this).addClass("bound");
         console.log('blur');
      });
    }
});

Upvotes: 0

Related Questions