开发者

Targeting a button on a form to press, with javascript

I know that, using Javascript, I can tell a form to submit using something like this:

do开发者_开发技巧cument.forms[0].submit()

However, if there are a number of forms on a page, which could be in any order, how would I target the submit link in this form:

<form action="/services/auth/" method="post">
<div id="auth-allow-container" class="button-container">
<a class="Butt" id="auth-allow" type="submit" href="#"><span>SUBMIT</span></a>
<a class="Butt CancelButt" id="auth-disallow" href="#home"><span>CANCEL</span></a>
</div>
</form>

..so that it is as if the user has clicked SUBMIT?


You could make a function:

function submitFormById(id) {
    var el = document.getElementById(id);
    while ( el && el.tagName.toLowerCase() != 'form') {
        el = el.parentNode;
    }
    el && el.submit();
}

Then you use this function like so:

submitFormById('auth-allow');
submitFormById('auth-disallow');

Both will submit the form.


Give the form a name attribute. Then you can do document.name.submit(). i.e.

<form name="MyForm" ....>
<input ... />
</form>

You would then be able to do document.MyForm.submit()

EDIT:

As you have said you can't change the html, solutions adding an ID are also no help. You will have to identify which numerical form element on the page this specific one is and do docuemnt.forms[x].submit() where x is the index of this form.


put in the link:

onclick="this.parentNode.parentNode.submit();"

this is a bit fragile if you change the dom structure but it is a generic link for this kind of form

update:

document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("auth-allow").addEventListener("click", submithAuthForm, false);
}, false);

function submithAuthForm(){
    document.getElementById('auth-allow').parentNode.parentNode.submit();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜