简体   繁体   中英

Which element to attach submit/onsubmit event handler to?

What element here is the form object that i can attach a submit/onsubmit eventHandler too? I'm making a chrome extension that modifies a website so I don't exactly have access to the direct website code outside of inspect element.

Inspect Element Breakdown

<div class="search-inner" role="form">

I assume that its the highlighted one, and I'm using this code to try getting a reaction out of the eventListener, but it doesn't seem to activate.

const form = document.getElementsByClassName("search-inner");
if(form != null && form.length > 0){
    form[0].addEventListener('onsubmit', run);
}

function run(event){
    console.log("hi");
    event.preventDefault();
}

The website does set up the form so that it does get hidden after submission, in case that affects the onsubmit eventHandler.

Adding the role attribute to elements only communicates their role to assistive technology, to tell users what they can expect in terms of the element's behaviour, and to add it to document outlines. It does not actually change an element's behaviour.

That's why we should rely on semantic HTML elements whenever we can.

If a <form> doesn't have an action attribute, it's quite likely that it never gets submitted, but that its controls trigger changes based on other events. This is quite common in today's reactive pages.

So if you actually want to target any form element that induces change to the DOM, it will get complicated, as most of the time they are not correctly grouped, neither with a form, nor with a <fieldset> .

Depending on what you're trying to achieve, you could look for buttons in the form and bind to their click events.

// kind of selector you’d need to implement
form, [role="form"], [role="search"], fieldset {
  button, input[type="button"], input[type="submit"] {
  }
}

Unfortunately it is not really possible to check for registered event handlers on elements .

So, as @xOxxOm suggested, you might also listen for change events on the document level, maybe as an additional measure to see whether a button click inside the form changed something.


Btw, the form from your example is not valid, since it's lacking its obligatory accessible name.

Also, it's a search form, so the search role might be more appropriate, which doesn't require a name, and you might consider it as well for your extension.

This is how the example should have been

<div class="search-inner" role="form" aria-labelledby="search-legend">
  <fieldset>
    <legend id="search-legend">

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