Search code examples
javascripthtmlformsstruts

Difference between JavaScript form submit and a form containing a submit button


I need a theoretic clarification...What's the difference between JavaScript form submit and a form containing a submit button?

(I'm using the framework Struts, but I think it doesn't affect the behaviour.)

I mean, this is my example, what's the difference between submit a form with a input type="submit"?

<html:form action="search.do?method=mySearch" method="post" styleId="searchFilterForm">
    <input type="hidden" name="myfield" value="">
    <table border="0" class="filterclass" width="530px">
        <tr>
            <td class="filterheader" align="center">
                <input type="submit" onclick="doMySubmit()" name="MyList" value="SEND" class="button actionbutton" />
            </td>
        </tr>
    </table>
</html:form>

function doMySubmit() {
    var myform = document.getElementById('searchFilterForm');
    myform.myfield.value = "Hello World";
}

And submitting the form with a submit inside JavaScript?

<html:form action="search.do?method=mySearch" method="post" styleId="searchFilterForm">
    <table border="0" class="filterclass" width="530px">
        <tr>
            <td class="filterheader" align="center">
                <input type="button" onclick="doMySubmit()" name="MyList" value="SEND" class="button actionbutton" />
            </td>
        </tr>
    </table>
</html:form>

function doMySubmit() {
    var myform = document.getElementById('searchFilterForm');
    myform.myfield.value = "Hello World";
    myform.submit();
}

Solution

  • The most notable difference is that when submitting a form by clicking a submit button there'll be a request parameter corresponding to the button that was clicked. So, in your example, with the submit button there'd be a request parameter with a name of MyList and a value of SEND. If you call form.submit() in JavaScript there won't be.

    So if you called request.getParameter("MyList"); on your server-side, with the first method that will return a String with the value SEND and with the second it will return null. This becomes important when you want to control the flow through your Action based on whether or not the form has been submitted, or even which button was used to submit the form (if you had several).