Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

javascript - Is there a better jQuery solution to this.form.submit();?

I want to trigger the submit event of the form the current element is in. A method I know works sometimes is:

this.form.submit();

I'm wondering if there is a better solution, possibly using jQuery, as I'm not 100% sure method works in every browser.

Edit:

The situation I have is, as follows:

<form method="get">
    <p><label>Field Label
        <select onchange="this.form.submit();">
            <option value="blah">Blah</option>
            ....
        </select></label>
    </p>
</form>

I want to be able to submit the form on change of the <select>.

What I'm looking for is a solution that works on any field within any form without knowing the id or name on the form. $('form:first') and $('form') won't work because the form could be the third on the page. Also, I am using jQuery on the site already, so using a bit of jQuery is not a big deal.

So, is there a way to have jQuery retrieve the form the input/select/textarea is in?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think what you are looking for is something like this:

$(field).closest("form").submit();

For example, to handle the onchange event, you would have this:

$(select your fields here).change(function() {
    $(this).closest("form").submit();
});

If, for some reason you aren't using jQuery 1.3 or above, you can call parents instead of closest.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...