Alec
Alec

Reputation: 9078

jQuery's focus() gets triggered again on a blur()

Say I have an input field "lastname", but I don't want people to insert something if the "firstname" field is still empty. Example: http://jsfiddle.net/GQyHp/

$('input[name=lastname]').focus(function() {
  if (!$('input[name=firstname]').val()) {
    alert('First enter your first name');
    $(this).blur();
  }
});

If I click the "lastname" field I get the popup, but after I click 'OK' it fires the same popup again. If I remove the blur() there's no second popup.

How can I prevent this thing from being triggered by the blur() function?

Upvotes: 3

Views: 933

Answers (1)

Zafer
Zafer

Reputation: 2190

I think the problem is related to alert().

When the alert box is closed, the focus is given to the control which was last focused by the user. This is my observation. Remove alert from the code at http://jsfiddle.net/GQyHp/1/ which is created by patrick and you'll see it will work.

So, not using built-in alert, instead using a fancy box for example may be a solution.

Upvotes: 2

Related Questions