Skip to content Skip to sidebar Skip to footer

Click() A Button Named 'submit' In Javascript

I have this HTML: I'd like to click() it. I can not change anything on the HTML-side. Whe

Solution 1:

NOTE: NEVER call anything in a form "submit"! It will hide the form's submit event from script.

You have many ways of accessing the button

document.querySelector("[name=submit]").click(); // first named buttondocument.querySelector("#form [name=submit]").click(); // in form with id="form"

Old IEs would shadow the name so you could use getElementById on a name but it is not recommended.

Older methods:

document.getElementsByName("submit")[0].click();

where 0 is the first element on the page named submit.

document.forms[0].elements[0].click(); 

where forms[0] is the first form and elements[0] is the first element

or

document.getElementsByTagName("form")[0].elements[0].click(); 

where ("form")[0] is the first form on the page and elements[0] is the first element

Solution 2:

Since you can't edit the actual HTML (to add the id attribute), and you want this to be cross-browser, you could loop over all of the input elements and check the type and value attributes until it matches your submit button:

functionget_submit_button() {
    var inputs = document.getElementsByTagName('INPUT');
    for(var i=0; i < inputs.length; i++) {
        var inp = inputs[i];
        if(inp.type != 'submit') continue;
        if(inp.value == 'Invoeren' && inp.name == 'submit') {
            return inp;
            break; // exits the loop
        }
    }
    returnfalse;
}

functionclick_submit() {
    var inp = get_submit_button();
    if(inp) inp.click();
}

Solution 3:

You are using getElementById but you don't have an id attribute on your input. Just because IE totally fubars the namespace and treats name attributes somewhat like id attributes does not mean that you should.

<inputid="submit" ... />
...
document.getElementById('submit').click();

Solution 4:

The immediate issue i can see is that you have NOT assigned id submit to your input, so this won't work:

document.getElementById("submit").........

unless you specify the id as well:

<inputid="submit"type="submit" name="submit" value="Invoeren" accesskey="s"class="buttons"/>

Solution 5:

There is no element with the ID "submit" -- you have an element named "submit". As Dylan points out, jQuery would make everything easier, but you can fix it yourself. If you cannot change the HTML, do something like this:

var buttons = document.getElementsByTagName("submit");
for (var i=0; i < buttons.length; i++) {
  var button = buttons[i];
  if (button.getAttribute("name") === "submit") {
     button.onclick = whatever ...

Post a Comment for "Click() A Button Named 'submit' In Javascript"