Enviar formulario usando un botón fuera de la etiqueta


Digamos que tengo:

<form method="get" action="something.php">
    <input type="text" name="name" />
</form>

<input type="submit" />

¿Cómo puedo enviar ese formulario con ese botón de envío fuera del formulario, creo que en HTML5 hay un atributo de acción para el envío, pero no estoy seguro de si eso es completamente cross-browser y si no lo es ¿hay de todos modos para hacer esto?

 208
Author: Mrchief, 2011-08-11

11 answers

Por lo que sé, no se puede hacer esto sin javascript.

Esto es lo que dice la especificación

Los elementos utilizados para crear controles generalmente aparecen dentro de un FORMULARIO elemento, pero también puede aparecer fuera de una declaración de elemento de formulario cuando se utilizan para construir interfaces de usuario. Esto se discute en el sección sobre eventos intrínsecos. Tenga en cuenta que los controles fuera de un formulario no pueden ser controles exitosos.

Esa es mi negrita

A el botón submit se considera un control.

Http://www.w3.org/TR/html4/interact/forms.html#h-17.2.1

De los comentarios

Tengo un área de configuración con varias pestañas con un botón para actualizar todo, debido para el diseño de la misma el botón estaría fuera de la forma.

¿Por qué no colocar el input dentro del formulario, pero usar CSS para colocarlo en otro lugar de la página?

 56
Author: Jason Gennaro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-11 04:09:12

En HTML5, existe el atributo form. Básicamente

<form id="myform" method="get" action="something.php">
    <input type="text" name="name" />
</form>

<input type="submit" form="myform" />
 463
Author: Lie Ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-24 14:56:58

Una solución que funciona muy bien para mí, todavía falta aquí. Requiere tener un elemento visualmente oculto <submit> o <input type="submit"> dentro del <form>, y un elemento asociado <label> fuera de él. Se vería así:

<form method="get" action="something.php">
     <input type="text" name="name" />
     <input type="submit" id="submit-form" class="hidden" />
</form>

<label for="submit-form" tabindex="0">Submit</label>

Ahora este enlace le permite 'hacer clic' en el elemento form <submit> haciendo clic en el elemento <label>.

 266
Author: Offereins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-06 13:33:17

Si puedes usar jQuery puedes usar esto

<form method="get" action="something.php" id="myForm">
    <input type="text" name="name" />

    <input type="submit" style="display:none" />
</form>

<input type="button" value="Submit" id="myButton" />

<script type="text/javascript">
    $(document).ready(function() {
       $("#myButton").click(function() {
           $("#myForm").submit();
       });
    });
</script>

Entonces, la línea de fondo es crear un botón como Enviar, y poner el botón enviar real en el formulario(por supuesto, ocultándolo), y enviar formulario por jquery haciendo clic en el botón 'Enviar falso'. Espero que ayude.

 41
Author: dav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-15 18:29:42
<form method="get" id="form1" action="something.php">

</form>

<!-- External button-->
<button type="submit" form="form1">Click me!</button>

Esto funcionó para mí, tener un botón de envío remoto para un formulario.

 29
Author: Joe the Squirrel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-03 20:35:01

Prueba esto:

<input type="submit" onclick="document.forms[0].submit();" />

Aunque sugeriría agregar un id al formulario y acceder por eso en lugar de document.forms[index].

 14
Author: Mrchief,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-11 04:00:08

Siempre puedes usar jQuery:

<form id="myForm">
  <!-- form controls -->
</form>
<input type="submit" id="myButton">

<script>
$(document).ready(function () {
  $("#myButton").click(function () {
    $("#myForm").submit();
  });
});
</script>
 10
Author: Aravind Suresh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-18 07:23:18

Aquí hay una solución bastante sólida que incorpora las mejores ideas hasta ahora, así como incluye mi solución a un problema resaltado con Offerein. No se utiliza javascript.

Si te importa la compatibilidad hacia atrás con IE (e incluso Edge 13), no puedes usar el form="your-form" atributo .

Use una entrada de envío estándar con display none y agregue una etiqueta fuera del formulario:

<form id="your-form">
  <input type="submit" id="your-form-submit" style="display: none;">
</form>

Tenga en cuenta el uso de display: none;. Esto es intencional. Usando la clase .hidden de bootstrap entra en conflicto con .show() y .hide() de jQuery, y desde entonces ha sido obsoleto en Bootstrap 4.

Ahora simplemente agrega una etiqueta para tu envío, (con estilo para bootstrap):

<label for="your-form-submit" role="button" class="btn btn-primary" tabindex="0">
  Submit
</label>

A diferencia de otras soluciones, también estoy usando tabindex - establecido en 0 - lo que significa que ahora somos compatibles con las pestañas del teclado. Agregar el atributo role="button" le da el estilo CSS cursor: pointer. Et voila. (Ver este violín).

 8
Author: Jonathan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-24 18:37:45

Similar a otra solución aquí, con modificaciones menores:

<form method="METHOD" id="FORMID">
   <!-- ...your inputs -->
</form>
<button type="submit" form="FORMID" value="Submit">Submit</button>

Https://www.w3schools.com/tags/att_form.asp

 7
Author: msterpka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-28 20:46:58

Esto funciona perfectamente! ;)

Esto se puede hacer usando Ajax y con I call: "a form mirror element". En lugar de enviar un formulario con un elemento fuera, puede crear un formulario falso. El formulario anterior no es necesario.

<!-- This will do the trick -->
<div >
    <input id="mirror_element" type="text" name="your_input_name">
    <input type="button" value="Send Form">
</div>

El código ajax sería como:

    <script>
        ajax_form_mirror("#mirror_element", "your_file.php", "#your_element_response", "POST");

        function ajax_form_mirror(form, file, element, method) {
            $(document).ready(function() {
                // Ajax
                $(form).change(function() { // catch the forms submit event
                    $.ajax({                // create an AJAX call...
                        data: $(this).serialize(),      // get the form data
                        type: method,                   // GET or POST
                        url: file,                      // the file to call
                        success: function (response) {   // on success..
                        $(element).html(response);  // update the DIV
                        }
                    });

                    return false; // cancel original event to prevent form submitting
                });
            });
        }
   </script>

Esto es muy útil si desea enviar algunos datos dentro de otro formulario sin enviar el formulario padre.

Tal vez este código pueda optimizar y arreglar más dependiendo del propósito. Funciona perfectamente!! ;) También funciona si desea un cuadro de opción de selección como este:

<div>
    <select id="mirror_element" name="your_input_name">
        <option id="1" value="1">A</option>
        <option id="2" value="2">B</option>
        <option id="3" value="3">C</option>
        <option id="4" value="4">D</option>
    </select>
</div>

Espero ayudar a alguien como me ayudó. ;)

 2
Author: Franks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-28 10:46:15

Tal vez esto podría funcionar, pero no se si es HTML válido.

<form method="get" action="something.php">
    <input type="text" name="name" />
    <input id="submitButton" type="submit" class="hide-submit" />
</form>

<label for="submitButton">Submit</label>
 1
Author: Emmanuel Lozoya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-11 22:05:30