views:

106

answers:

4

i want to call a function when i have a textfield focused and then unfocus it (whether i press TAB or click elsewhere with the mouse) and i used this code:

 $("#settings_view #my_profile_div input").focus(function() {
        $(this).blur(function() {
            change_my_profile();
        });
    });

when i first run it (have a field focused then unfocus it) it runs one time as expected. but the sencond time it calls the function change_my_profile twice. the 3rd time it ran 3 times and so on.

what is the problem here and how do i solve it (i tried with 'throw' after change_my_profile and then it only ran one time, but i want to locate the problem anyway).

+1  A: 

You need to remove the event handler after successful execution. Otherwise, you are stacking handler upon handler and they all get triggered. I think in JQuery that is done using unbind()

Pekka
+2  A: 

The .focus() and .blur() functions assign handlers to the 'focus' and 'blur' events repsectively. So every time the user focuses the textbox, your code is adding a new event handler to the 'blur' event. What you want is:

$("#settings_view #my_profile_div input").blur(change_my_profile);
Annabelle
I think the focus/blur combination is actually what he wants, but the bindings are not properly cleaned up. I may be mistaken, though.
Pekka
@Pekka: as you'll only get a blur event when an input has focus, if OP wants the focus/blur combination, then OP is mistaken. Registering just the blur handler is functionally equivalent.
outis
no you are correct...first focus a field..than blur and the function should run
weng
The blur event only occurs after focus, so the focus handling is unnecessary
Annabelle
Removed the extraneous anonymous function - thanks TM for pointing it out above. Too much eggnog I guess :P
Annabelle
A: 

Your code is asking jQuery to add (append) an onBlur event handler to an input field every time the user enters the field. So, your same event handler function gets appended over and over again. Are you simply trying to trigger a function to run when the user moves out of a field? If that is the case, you can simply use .blur to attach the onBlur handler once.

Ed Schembor
+5  A: 

it is binding a blur event every time a focus event is initiated, that's why you are getting multiple executions

try

$(this).bind("blur",function(){
  change_my_profile(this);
})

and then in your change_my_profile function do the following

function change_my_profile(el){
  $(el).unbind("blur");
  //rest of the change_my_profile code goes here
}
pǝlɐɥʞ