Skip to content Skip to sidebar Skip to footer

How Best To Make A Link Submit A Form

What's the best way to get a regular anchor () to submit the form it is embedded in when clicked?
  • <

Solution 1:

Solution 2:

Solution 3:

I am using this now every time. Because the submit button in my project usually a link (by wrap an image or CSS), so I use this:

<a href="#" onclick="$(this).closest('form').submit(); return false;">Submit</a>

Don't forget it is using jQuery too.

You can wrap in your own function. So it always submit the parent element (form) on that link.

Solution 4:

As long as the link is a direct child of the form, you can use this. You don't need to know the name of the form. Works in at least Firefox and Chrome.

<formaction=""><ahref=""onclick="parentNode.submit();return false;">Submit</a></form>

quirksmode.org tells me x.parentNode works in all browsers, so this should work everywhere.

Solution 5:

loop through parent nodes until you find an element with tagname that indicates it's a form!

<form><ul><li><p>
                The link could be <span>embedded <ahref=""onclick="get_form(this).submit(); return false">at any level</a></span>
                in the form, so "this.parentNode.parentNode..." is no good. :(
            </p></li></ul></form><scripttype="text/javascript">//<![CDATA[functionget_form( element )
    {
        while( element )
        {
            element = element.parentNodeif( element.tagName.toLowerCase() == "form" )
            {
                //alert( element ) //debug/testreturn element
            }
        }
        return0; //error: no form found in ancestors
    }
    //]]></script>

Post a Comment for "How Best To Make A Link Submit A Form"