简体   繁体   中英

Prevent focus on button click in plain javascript

I am facing more or less the same problem described here , (ie I have a submit input which is clicked programmatically when it gains focus after a tab, but the focus handler is also invoked when the user clicks on the button, causing a double submit). The solution suggested in the linked post works, but I need one which does not require jQuery. Does anyone have some thoughts on that? Please note that I need the button's click behavior to remain the same, as it is binded to an asp .net server-side event. Thank you!

You'll want to prevent the form from submitting so add an event listener and then code how you want JavaScript to handle submitting the form. Also +1 to your question for asking how to competently code this without depending on any frameworks! :-)

Some rough code to give you an idea of how to prevent a form from submitting...

if (window.addEventListener)
{
 forms[i].addEventListener('submit',function(e) {e.preventDefault(); eval(id_forms[e.target.id]+'();');},false);
}
else if (window.attachEvent)
{
 forms[i].attachEvent('onsubmit',function(e,f) {e.returnValue=false; eval(id_forms[e.srcElement.id]+'();');});
}

I ended up with having a keyUp and keyDown handler in which I set/unset a isKeyPressed variable. It is my understanding that the sequence of events that happens when tabbing is the following:

  • keyDown
  • focus gained
  • keyUp

Thus, in the focus event handler I check if the focus was gained by tabbing (ie if the isKeyPressed is set to true) and submit the form there. Otherwise, if the focus was gained after a click(), the isKeyPressed will not be set to true, and I will not trigger the form submission programatically.

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