11

By the following code I wish to "DO SOMETHING" on "ONBLUR" of element id="eg1" only if the onblur event was not caused due to "ONCLICK" on the submit button.

    $(document).ready(function() {  
     $('#eg1').blur(function() {
      if(!($("#SubmitBut").click())) {
             //do something
      }
     });
    });

For Eg : if the user changes value of the “eg1” text field and clicks on the next text field then the DO SOMETHING code must run, but in case the user changes value of the the “eg1” field and then clicks on the SUBMIT button, then the DO SOMETHING code must not run.

Is it the correct way to do so ?? Please guide.

Palak Taneja
  • 1,983
  • 3
  • 13
  • 12

4 Answers4

35

blur event of an element triggers before click event of another. So one way is to use mousedown and mouseup events to toggle a flag, because mousedown event of one element triggers before blur event of another one.

$("#eg1").on("blur", function(e){
  if($("#submit").data("mouseDown") != true){
      alert("DO SOMETHING");
  }
});

$("#submit").on("mousedown", function(e){
    $("#submit").data("mouseDown", true);
  });

$("#submit").on("mouseup", function(e){
    $("#submit").data("mouseDown", false);
  });
Diode
  • 24,570
  • 8
  • 40
  • 51
0

Update:

$('input[type="submit"]').mousedown(test);

Have a look at this fiddle JSFiddle to address your problem. Use the console to view the events triggered and suppressed after specific actions are performed.

You should suppress the event handler that is bound to the text when click or submit is performed.

D3V
  • 1,543
  • 11
  • 21
0
A trick -

 $(document).ready(function() {  
var flag = false;
     $('#eg1').blur(function() {
flag = true;
      if(!($("#SubmitBut").click())) {
if(flag) 
   return false;            
 //do something
      }
     });
    });
A.T.
  • 24,694
  • 8
  • 47
  • 65
0

Answering this old question (since it came up for me first in Google). There was a more elegant solution described in this other S.O. question, which is to just call event.preventDefault() in the onMouseDown handler.

So in modern component frameworks:

<button onMouseDown={(e) => e.preventDefault()} /button>
trungly
  • 2,041
  • 1
  • 11
  • 8