How to submit a form using javascript?

2019-01-01 02:07发布

I have a form with id theForm which has the following div with a submit button inside:

<div id="placeOrder" 
     style="text-align: right; width: 100%; background-color: white;">
     <button type="submit" 
             class='input_submit' 
             style="margin-right: 15px;" 
             onClick="placeOrder()">Place Order
     </button>
</div>

When clicked, the function placeOrder() is called. The function changes the innerHTML of the above div to be "processing ..." (so the submit button is now gone).

The above code works, but now the problem is that I can't get the form to submit! I've tried putting this in the placeOrder() function:

document.theForm.submit();

But that doesn't work.

How can I get the form to submit?

标签: javascript
10条回答
明月照影归
2楼-- · 2019-01-01 02:42

You can use...

document.getElementById('theForm').submit();

...but don't replace the innerHTML. You could hide the form and then insert a processing... span which will appear in its place.

var form = document.getElementById('theForm');

form.style.display = 'none';

var processing = document.createElement('span');

processing.appendChild(document.createTextNode('processing ...'));

form.parentNode.insertBefore(processing, form);
查看更多
只靠听说
3楼-- · 2019-01-01 02:43

Set the name attribute of your form to "theForm" and your code will work.

查看更多
冷夜・残月
4楼-- · 2019-01-01 02:43
<html>
<body>

<p>Enter some text in the fields below, then press the "Submit form" button to submit the form.</p>

<form id="myForm" action="/action_page.php">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br><br>
  <input type="button" onclick="myFunction()" value="Submit form">
</form>

<script>
function myFunction() {
    document.getElementById("myForm").submit();
}
</script>

</body>
</html>
查看更多
梦寄多情
5楼-- · 2019-01-01 02:46

you can use below code to submit the form using Javascript;

document.getElementById('FormID').submit();
查看更多
只靠听说
6楼-- · 2019-01-01 02:52

It is an old post but I will leave the way I do to submit the form without using name tag inside the form:

HTML

<button type="submit" onClick="placeOrder(this.form)">Place Order</button>

JS

function placeOrder(form){
    form.submit();
}

Hope this solution can help somebody else. TQ

查看更多
与风俱净
7楼-- · 2019-01-01 02:53
//Take form name as "theForm"
//Example:   
         ## ----Html code----- ##    
      <form method="post" action="" name="theForm">
            <button onclick="placeOrder()">Place Order</button>
      </form>

            ## -------javascript code------ ##

        function placeOrder(){
        document.theForm.action="yourUrl";
        document.theForm.submit();
        }
查看更多
登录 后发表回答