2012-02-01 12 views
6

He creado una página php con dos formularios pero me gustaría tener solo un botón de envío para ambos formularios. los formularios tienen id s firstform & secondform. He probado otros scripts pero en realidad no funcionan.Cómo enviar 2 formularios en una sola página con un solo botón de envío

Aquí está mi código de abajo:

<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()"/> 
+1

has intentado 'return false' from' submitForms'? –

+0

@ DanielA.White no, no lo intenté, pero dónde devolverlo falso –

+1

Nuh-uh. Si lo envía, lo reenviará a la URL de acción a menos que envíe de vuelta algunas cosas que el navegador no pretende mostrar (un archivo que puede descargar). Puede usar javascript para enviar un mensaje de ajax post que contenga datos en cada formulario. – Alfabravo

Respuesta

6

Usted tiene problemas VARIAS

  1. entrada type = La imagen es un botón de envío por lo que está tratando de enviar algo de una forma no-existente, Probablemente la misma página que está en

  2. cuando envía form1, reemplaza la página actual, si logra enviar también Form2, es MUY probable que interfiera con el bmission de Form1

Aquí es lo que usted puede intentar (JavaScript natural):

<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 onclick="submitForms()"><img src="images/order-button.png" "/></button> 

alternativa AJAX las formas de una en una (asume jQuery cargado)

DEMO HERE

$(document).ready(function() { 
    $("#subbut").click(function() { 
     $.post($("#firstform").attr("action"), $("#firstform").serialize(), 
      function() { 
      $.post($("#secondform").attr("action"), $("#secondform").serialize(), 
       function() { 
       alert('Both forms submitted'); 
       }); 
      }); 
     }); 
    }); 

ACTUALIZACIÓN: Si desea que el contenido de dos de forma que se someterá a una acción, sólo tiene que añadir los serialises:

$(document).ready(function() { 
    $("#subbut").click(function() { 
     $.post($("#firstform").attr("action"), $("#firstform").serialize()+$("#secondform").serialize(), 
       function() { 
       alert('Both forms submitted'); 
       }); 
     }); 
    }); 

PS: El PHP en la demo se acaba haciendo eco de vuelta lo que se publica. No se necesita ninguna acción especial en el servidor.

+0

lo intento pero solo está funcionando la segunda forma –

+0

¿Has intentado cuál? – mplungjan

+0

_mplungjan_ pruebo ambos y cuando coloco el botón de enviar en primer formulario solo funciona, cuando coloco el botón de enviar en el segundo formulario entonces solo el segundo formulario funciona pero cuando coloco el botón de enviar al lado ambos formamos entonces nada trabajando –

2
  • Establecer el atributo "objetivo" en la primera forma de "_blank"
  • Ajuste el atributo "action" en la primera forma de "#Cerrar" (en lugar de "cerrar" con lo que quieras.
  • tener un script en la página que comprueba si el document.location.hash está "cerca" si es window.close()

Aquí está la jsFiddle demostrar.

http://jsfiddle.net/TqhPr/18/

HTML

<form id="f1" name="f1" target="_blank" method="POST" action="#close"> 
    <input type="hidden" value="1" /> 
    <input type="submit" id="s1" value="11" /> 
</form> 
<hr/> 
<form id="f2" name="f2" method="POST" action="#second_form"> 
    <input type="hidden" value="2" /> 
    <input type="submit" id="s2" value="22" /> 
</form> 
<hr/> 
<input type="button" id="both" value="Submit Both Forms" /> 

JavaScript

$(document).ready(function() { 
    $("#both").click(function() { 
     document.getElementById("f1").submit(); 
     document.getElementById("f2").submit(); 
    }); 
    if(document.location.hash == "#close") { 
     alert("closing the window caused by posting the first form"); 
     window.close(); 
    } 
    if(document.location.hash) { 
     alert(document.location.hash); 
    } 
}); 
+0

tanto el formulario enviado por separado, enviar ambos no funciona –

+0

¿Qué quiere decir con "enviado por separado" Sea más elaborado en sus comentarios – mplungjan

+0

_mplungjan_ cuando hago clic en el botón 11 me da el valor 1 y el mismo en el botón 22, pero cuando hago clic en "Enviar ambas formas" no funciona –

-1

Este código se publicaron correctamente 2 datos de los formularios con un solo botón enviar.

<SCRIPT LANGUAGE="JavaScript" type="text/javascript"> 
/* Collect all forms in document to one and post it */ 
function submitAllDocumentForms() { 
    var arrDocForms = document.getElementsByTagName('form'); 
    var formCollector = document.createElement("form"); 
    with(formCollector) 
    { 
     method = "post"; 
     action = "test.php"; 
     name = "formCollector"; 
     id = "formCollector"; 
    } 
    for(var ix = 0 ; ix < arrDocForms.length ; ix++) { 
     appendFormVals2Form(arrDocForms[ix], formCollector); 
    } 
    document.body.appendChild(formCollector); 
    formCollector.submit(); 
} 

/* Function: add all elements from frmCollectFrom and append them to 
      frmCollector before returning frmCollector*/ 
function appendFormVals2Form(frmCollectFrom, frmCollector) { 
    var frm = frmCollectFrom.elements; 
    for(var ix = 0 ; ix < frm.length ; ix++) 
     frmCollector.appendChild(frm[ix]); 
    return frmCollector; 
} 
</SCRIPT> 

<FORM METHOD=POST ACTION="test.php" NAME="form1" id="form1"> 
    <INPUT TYPE="text" NAME="box1" size="20" > 
</FORM> 
FORM2: 
<FORM METHOD=POST ACTION="test.php" NAME="form2" id="form2"> 
    <INPUT TYPE="text" NAME="box2" size="20" > 
</FORM> 

<INPUT TYPE="button" value="Submit Form 1 & 2" onClick="submitAllDocumentForms()"> 
+0

Genial, eso no es lo que preguntas. Usted solicitó enviar dos formularios y no cómo concatenar dos formularios en un solo envío. Ver mi actualización – mplungjan

+0

_mplungjan_ sí, tu demostración también es perfecta y muchas gracias por eso :) –

0

Lo usé para un problema similar. Quería crear una sola página para consultar varios sitios y revisar sus resultados en paralelo:

WordLookup.html (/ home/punto principal marco de entrada):

<html> 
 
    <head> 
 
    <title>Word Lookup</title> 
 
    </head> 
 
    <frameset cols="33%,34%,33%"> 
 
    <frame src="" name="DIC"> 
 
    <frameset rows="21,*"> 
 
     <frame src="frame.html" name="PRF"> 
 
     <frame src="" name="MW"> 
 
    </frameset> 
 
    <frame src="" name="TFD"> 
 
    </frameset> 
 
</html>

y luego esto para frame.html (javascript método):

<html> 
 
<head> 
 
<style> 
 
    body { margin: 0; background-color: #AAAAAA; } 
 
    table, td { padding: 0; border-collapse: collapse; margin-left: auto; margin-right: auto; } 
 
    form { padding: 0; margin: 0; } 
 
</style> 
 
<script> 
 
    function submitForms(){ 
 
    var x = document.getElementById("search3").value; 
 
    document.getElementById("fr1").setAttribute("value", x); 
 
    document.getElementById("DIC").submit(); 
 
    document.getElementById("fr2").setAttribute("value", x); 
 
    document.getElementById("MW").submit(); 
 
    document.getElementById("fr3").setAttribute("value", x); 
 
    document.getElementById("TFD").submit(); 
 
    document.getElementById("search3").value = ""; 
 
    } 
 
</script> 
 
</head> 
 

 
<body> 
 

 
    <table> 
 
    <tr> 
 
     <td> 
 
     <input id="search3" type="text" placeholder="3x Search" onclick="value=''" onkeydown="if (event.keyCode == 13) 
 
{submitForms()}" autofocus="1"> 
 
     </td> 
 
     <td> 
 
     <form action="http://www.dictionary.com/dic" target="DIC" id="DIC"> 
 
      <input id="fr1" name="q" type="hidden" placeholder="Dictionary" onclick="value=''"> 
 
     </form> 
 
     </td> 
 
     <td> 
 
     <form action="https://www.merriam-webster.com/dictionary" target="MW" id="MW"> 
 
      <input id="fr2" name="s" type="hidden" placeholder="Merriam-Webster" onclick="value=''"> 
 
     </form> 
 
     </td> 
 
     <td> 
 
     <form action="//www.thefreedictionary.com/_/search.aspx" target="TFD" id="TFD"> 
 
      <input id="fr3" name="word" type="hidden" placeholder="TheFreeDictionary" onclick="value=''"> 
 
     </form> 
 
     </td> 
 
    </tr> 
 
    </table> 
 
</body> 
 
</html>
siento si esto es un poco prolijo, pero es un ejemplo de trabajo (en Chrome 56ish).

Cuestiones relacionadas