views:

43

answers:

3

I want to submit a simple asp.net form in jQuery

can I assume

$("form[0]").submit()

always works, cross browser?

+1  A: 

You mean something like this

$("#aspnetForm").submit()

Something like above would work cross browser as you said

The code you pasted is cross browser too. It won't work on ANY browser so maybe that counts as cross browser :-) just a joke

Claudio Redi
A: 

These will:

$("#aspnetForm").submit()

or

var theForm = document.forms['aspnetForm'];
theForm.submit()
Raj Kaimal
A: 

No, you can't assume this. $("form[0]").submit() will submit the first form on the page. However, you can have more than one form on an ASP.NET page, though only one of these forms can be a server-side form (with runat="server" attribute).

If what you want is to submit the server-side form on an ASP.NET page then I think the best way would be to do it in code-behind by registering a script. It's a bit more hassle, but should always work (and when there is no server-side form it will detect it). Something like this:

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);

    if (this.Form != null)
    {
        string js = String.Format("$('#{0}').submit()", this.Form.ClientID);
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Submit", js, true);
    }
}
Dan Diplo
Dan, that's not what that selector will select. See my comment on the question.
Matt Ball
I didn't bother to check that, I must admit! However, the point is, the code I posted *will* work and will work regardless of what ID you give to the form since it dynamically assigns it based on the actual ID. Hard-coding ID names in web-forms is rarely a good idea (unless you are using ASP.NET 4.0)
Dan Diplo