简体   繁体   中英

How to get the active element of a HTML page in Javascript

I have a HTML page which has only one input text box and one button just after that. I have put onblur event handler for the input text box where I am calling an ajax call which does only validation and then shows the error. Similarly, I have put onclick event on the button where I am again calling the different Ajax call which also does validation and if validation passes then it does some DB update also and then redirect to someother URL.

My requirement is if the user has focus on the input box and then he simply clicks on the button(without loosing the focus) then only button ajax call should fire. However, I am seeing two ajax calls one for onblur and one for onclick is firing.

I tried using event.relatedtarget in the onblur to see if it is generating on the click of button. But it works only in chrome. I checked document.activeelement also. This also doesn't work.

Please let us know how can we handle this in all the browser.

Thanks, Sourabh

You could set a global flag like this

var submitting = false;
$('#button').click(function(){
    if (!submitting) {
        submitting = true;
        $.ajax({
           url: 'whateverurl.php',
           success: function(data) {
               submitting = false;
           }
        });
    }
});

This is sudo code since I don't know your source, you would do the same thing for your onblur

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM