Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent other event handlers, from first handler, in jQuery

Tags:

jquery

I have input field and submit button on page.

<form id="searchform">
<input id="s" type="search" autocomplete="off" name="s" value="">
<div id="search-submit" class="input-group-addon">
    <i>SUBMIT</i>
</div>
</form>

and here is jQuery code:

var inProgress = false; 

$("#search-submit").on("click", function() {
    inProgress = true;
    alert ("Form Submit");
    inProgress = false;   
});

$("#s").blur(function () {
    if ( ! inProgress ) {
        alert ("Blur");
    inProgress = false; 
    }
});

I would like to prevent blur if clicked from input field to Submit div, but want to allow it if clicked from input field to some other part of page. I can't use button for submit.

I have put up the fiddle jsfiddle.net/405kzboh/1

But now I even don't understand why Click event is not triggered before the Blur event if someone click from input to Submit!

like image 597
Dampas Avatar asked Oct 19 '22 17:10

Dampas


1 Answers

The mousedown event on the target element will be called before the blur event on the textbox so you can hook into that event to set your in progress flag.

var inProgress = false; 

$("#search-submit").on("mousedown", function() {
    inProgress = true;
});

$("#search-submit").on("click", function() {
    console.log ("Form Submit");
    inProgress = false;   
});

$("#s").on("blur", function () {
    if ( ! inProgress ) {
        console.log ("Blur");
    }
});

I've updated the fiddle: http://jsfiddle.net/405kzboh/2/

like image 133
DoctorMick Avatar answered Oct 22 '22 20:10

DoctorMick