Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

javascript - How to submit 2 forms in one page with a single submit button

I've created a php page with two forms but I would like to have only one submit button for both forms. the forms have the ids firstform & secondform. I have tried other scripts but they don't really work.

Here is my code below:

<script language="javascript">
submitForms = function(){
    document.getElementById("firstform").submit();
    document.getElementById("secondform").submit();
}

</script>

<input type="image" src="images/order-button.png" name="button" value="Submit" onclick="submitForms()"/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have SEVERAL issues

  1. input type=image IS a submit button so you are trying to submit something from a non-existing form, likely the same page you are on

  2. when you submit form1, it replaces the current page, if you manage to submit form2 as well, it is VERY likely to interfere with the submission of form1

Here is what you can TRY (plain javascript):

<script language="javascript">
function submitForms() {
  document.getElementById("firstform").submit();
  document.getElementById("secondform").submit();
 }
</script>

<form id="firstform" target="iframe1">
</form><iframe name="iframe1" style="display:none"></iframe>
<form id="secondform" target="iframe2">
</form><iframe name="iframe1" style="display:none"></iframe>
<button typ"button" onclick="submitForms()"><img src="images/order-button.png" "/></button>

Alternatively AJAX the forms one at a time (assumes jQuery loaded)

DEMO HERE

$(document).ready(function() {
  $("#subbut").click(function(e) {
    e.preventDefault(); // or make the button type=button
    $.post($("#firstform").attr("action"), $("#firstform").serialize(), function() {
      $.post($("#secondform").attr("action"), $("#secondform").serialize(),
        function() {
          alert('Both forms submitted');
        });
    });
  });
});

UPDATE: If you want two form's content to be submitted to one action, just add the serialises:

$(document).ready(function() {
  $("#subbut").click(function(e) {
    e.preventDefault(); // or make the button type=button
    $.post($("#firstform").attr("action"), $("#firstform").serialize() + $("#secondform").serialize(), function() {
      alert('Both forms submitted');
    });
  });
});

PS: The PHP in the demo is just echoing back what you post. There is no special action needed on the server.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...