JS - How to submit form onclick and send submit button

29,514

Solution 1

You can do with javascript form method

<button onclick="document.forms[0].submit()"></button>

if you have multiple forms in the document then set id to the form

<form id="form1">
  <input name="data" type="text">
  <input type="submit" name="send" id="send-button" style="display: none">
</form>
<button onclick="document.getElementById("form1").submit()"></button>

Solution 2

Give the form a name:

    <form name="myform">
        <a href="javascript: submitform()">Submit</a>
    </form>

Submit form function:

    <script type="text/javascript">
        function submitform()
        {
           document.myform.submit();
        }
    </script>

Invoke submission:

    document.forms["myform"].submit();
Share:
29,514
MakoBuk
Author by

MakoBuk

Updated on September 24, 2020

Comments

  • MakoBuk
    MakoBuk over 3 years

    I need to submit form by button which is out of scope of the form by JavaSript.

    <form>
      <input name="data" type="text">
      <input type="submit" name="send" id="send-button" style="display: none">
    </form>
    
    <button onclick="$('#send-button').click() || .submit()"></button>
    

    The button #send-button is visible and I need to send whole form to server. It means I receive $data and $send (both).

    Now I am getting just the $data.

    Any idea?

  • Luis González
    Luis González over 8 years
    He is saying that he wants to receive the button in server, he already now how send the form using onclick event
  • MakoBuk
    MakoBuk over 8 years
    Oh, sorry. Now I tried to run it on JsFiddle and it works how I assumed. The problem is somewhere in my other JS libraries probably :-( When you look at request data, there are data input and submitted button name...