Múltiples botones de envío en un formulario HTML


Supongamos que crea un asistente en un formulario HTML. Un botón retrocede y otro avanza. Dado que el botón back aparece primero en el marcado cuando presiona Enter, usará ese botón para enviar el formulario.

Ejemplo:

<form>
  <!-- put your cursor in this field and press Enter -->
  <input type="text" name="field1" />

  <!-- This is the button that will submit -->
  <input type="submit" name="prev" value="Previous Page" />

  <!-- But this is the button that I WANT to submit -->
  <input type="submit" name="next" value="Next Page" />
</form>

Lo que me gustaría hacer, es llegar a decidir qué botón se utiliza para enviar el formulario cuando un usuario presiona Enter. De esta manera, al presionar Enter, el Asistente se moverá a la página siguiente, no a la anterior. ¿Tienes que hacerlo? ¿usar tabindex para hacer esto?

Author: Sasha, 2008-08-01

23 answers

Espero que esto ayude. Solo estoy haciendo el truco de floating los botones de la derecha.

De esta manera, el botón Anterior queda a la izquierda del botón Siguiente, pero el Siguiente aparece primero en el código HTML:

.f {
  float: right;
}
.clr {
  clear: both;
}
<form action="action" method="get">
  <input type="text" name="abc">
  <div id="buttons">
    <input type="submit" class="f" name="next" value="Next">
    <input type="submit" class="f" name="prev" value="Prev">
    <div class="clr"></div><!-- This div prevents later elements from floating with the buttons. Keeps them 'inside' div#buttons -->
  </div>
</form>

Editar: Beneficios sobre otras sugerencias: sin JavaScript, accesible, ambos botones permanecen type="submit"

 133
Author: palotasb,
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-02-15 21:23:34

¿Sería posible para usted cambiar el tipo de botón anterior en un botón como este:

<input type="button" name="prev" value="Previous Page" />

Ahora el botón Siguiente sería el predeterminado, además también podría agregar el atributo default para que su navegador lo resalte de la siguiente manera:

<input type="submit" name="next" value="Next Page" default />

Espero que eso ayude.

 61
Author: Wally Lawless,
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-06 22:50:09

Dale a tus botones de envío el mismo nombre de esta manera:

<input type="submit" name="submitButton" value="Previous Page" />
<input type="submit" name="submitButton" value="Next Page" />

Cuando el usuario presiona enter y la solicitud va al servidor, puede verificar el valor de submitButton en su código del lado del servidor que contiene una colección de pares de formularios name/value. Por ejemplo en ASP clásico:

If Request.Form("submitButton") = "Previous Page" Then
    ' Code for Previous Page
ElseIf Request.Form("submitButton") = "Next Page" Then
    ' Code for Next Page
End If

Referencia: Usando múltiples botones de envío en un solo formulario

 54
Author: huseyint,
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
2014-07-14 07:55:42

Si el hecho de que el primer botón se usa por defecto es consistente en todos los navegadores, ¿por qué no colocarlos correctamente en el código fuente y luego usar CSS para cambiar sus posiciones aparentes? float ellos izquierda y derecha para cambiarlos visualmente, por ejemplo.

 31
Author: Polsonby,
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-10-14 12:21:12

Si realmente solo quieres que funcione como un cuadro de diálogo de instalación, qué tal si solo le das foco al botón "Siguiente" OnLoad. De esta manera, si el usuario pulsa Return, el formulario envía y sigue adelante. Si quieren volver, pueden presionar Tab o hacer clic en el botón.

 17
Author: Scott Gottreu,
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
2008-08-26 03:41:44

Puede funcionar con CSS

Póngalos en el marcado como el botón siguiente primero, luego el botón anterior siguiente.

Luego use CSS para colocarlos para que aparezcan de la manera que desee

 17
Author: qui,
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
2008-09-16 12:16:05

A veces la solución proporcionada por @palotasb no es suficiente. Hay casos de uso en los que, por ejemplo, un botón de envío "Filtro" se coloca encima de botones como "Siguiente y anterior". Encontré una solución para esto: copie el botón de envío que debe actuar como el botón de envío predeterminado en un div oculto y colóquelo dentro del formulario encima de cualquier otro botón de envío. Técnicamente, será enviado por un botón diferente al presionar Enter y luego al hacer clic en el botón visible Siguiente. Pero dado que el nombre y el valor son los mismos, no hay diferencia en el resultado.

<html>
<head>
    <style>
        div.defaultsubmitbutton {
            display: none;
        }
    </style>
</head>
<body>
    <form action="action" method="get">
        <div class="defaultsubmitbutton">
            <input type="submit" name="next" value="Next">
        </div>
        <p><input type="text" name="filter"><input type="submit" value="Filter"></p>
        <p>Filtered results</p>
        <input type="radio" name="choice" value="1">Filtered result 1
        <input type="radio" name="choice" value="2">Filtered result 2
        <input type="radio" name="choice" value="3">Filtered result 3
        <div>                
            <input type="submit" name="prev" value="Prev">
            <input type="submit" name="next" value="Next">
        </div>
    </form>
</body>
</html>
 17
Author: netiul,
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-10-26 09:53:08

Kevin, esto no se puede hacer con HTML puro. Debes confiar en JavaScript para este truco.

Sin embargo, si coloca dos formularios en la página HTML, puede hacerlo.

Form1 tendría el botón anterior.

Form2 tendría cualquier entrada de usuario + el botón siguiente.

Cuando el usuario presiona Enter en Form2, se disparará el Siguiente botón de envío.

 17
Author: FlySwat,
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-01 18:41:04

Usaría Javascript para enviar el formulario. La función se activaría por el evento OnKeyPress del elemento form, y detectaría si la tecla Enter estaba seleccionada. Si este es el caso, enviará el formulario.

Aquí hay dos páginas que dan las técnicas sobre cómo hacer esto: 1, 2. Basado en estos, aquí hay un ejemplo de uso (basado en aquí):

<SCRIPT TYPE="text/javascript"><!--
function submitenter(myfield,e) {
  var keycode;
  if (window.event) {
    keycode = window.event.keyCode;
  } else if (e) { 
    keycode = e.which;
  } else {
    return true;
  }

  if (keycode == 13) {
    myfield.form.submit();
    return false;
  } else {
    return true;
  }
}
//--></SCRIPT>

<INPUT NAME="MyText" TYPE="Text" onKeyPress="return submitenter(this,event)" />
 16
Author: Yaakov Ellis,
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
2008-08-03 13:12:21

Kevin,

Esto funciona sin javascript o CSS en la mayoría de los navegadores:

<form>
<p><input type="text" name="field1" /></p>
<p><a href="previous.html">
<button type="button">Previous Page</button></a>
<button type="submit">Next Page</button></p>
</form>

Firefox, Opera, Safari, Google Chrome todos funcionan.
Como siempre, IE es el problema.

Esta versión funciona cuando javascript está activado:

<form>
<p><input type="text" name="field1" /></p>
<p><a href="previous.html">
<button type="button" onclick="window.location='previous.html'">Previous Page</button></a>
<button type="submit">Next Page</button></p>
</form>

Así que el defecto en esta solución es:
La página anterior no funciona si utiliza IE con Javascript desactivado.
¡Eso sí, el botón de atrás sigue funcionando!

 14
Author: Jolyon,
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
2008-09-16 12:12:37

Si tienes varios botones activos en una página, entonces puedes hacer algo como esto:

Marque el primer botón que desea activar en Ingrese presione como botón predeterminado en el formulario. Para el segundo botón asociarlo a Backspace botón en el teclado. Retroceso el código de evento es 8.

$(document).on("keydown", function(event) {
  if (event.which.toString() == "8") {
    var findActiveElementsClosestForm = $(document.activeElement).closest("form");

    if (findActiveElementsClosestForm && findActiveElementsClosestForm.length) {
      $("form#" + findActiveElementsClosestForm[0].id + " .secondary_button").trigger("click");
    }
  }
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>

<form action="action" method="get" defaultbutton="TriggerOnEnter">
  <input type="submit" id="PreviousButton" name="prev" value="Prev" class="secondary_button" />
  <input type="submit" id='TriggerOnEnter' name="next" value="Next" class="primary_button" />
</form>

Espero que esto ayude.

 13
Author: user1591131,
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-04-11 20:50:34

Cambiar el orden de tabulación debería ser todo lo que se necesita para lograr esto. Hazlo simple.

Otra opción simple sería poner el botón atrás después del botón enviar en el código HTML, pero flotarlo hacia la izquierda para que aparezca en la página antes del botón enviar.

 12
Author: Kenny Johnson,
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-11-27 22:27:41

Otra opción simple sería poner el botón atrás después del botón enviar en el código HTML, pero flotarlo hacia la izquierda para que aparezca en la página antes del botón enviar.

Cambiar el orden de tabulación debería ser todo lo que se necesita para lograr esto. Hazlo simple.

 12
Author: ,
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
2014-10-14 16:02:21

Mantenga el nombre de todos los botones de envío igual "" prev " La única diferencia es el atributo value con valores únicos. Cuando creamos el script, estos valores únicos nos ayudarán a averiguar cuál de los botones de envío se presionó.

Y escriba la siguiente codificación:

    btnID = ""
if Request.Form("prev") = "Previous Page" then
    btnID = "1"
else if Request.Form("prev") = "Next Page" then
    btnID = "2"
end if
 11
Author: jayu,
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-10-14 12:22:00

Esto es lo que he probado: 1. Debe asegurarse de darle a sus botones diferentes nombres 2. Escriba una instrucción if que hará la acción requerida si se hace clic en cualquiera de los botones.

<form>
<input type="text" name="field1" /> <!-- put your cursor in this field and press Enter -->

<input type="submit" name="prev" value="Previous Page" /> <!-- This is the button that will submit -->
<input type="submit" name="next" value="Next Page" /> <!-- But this is the button that I WANT to submit -->
</form>

En PHP,

if(isset($_POST['prev']))
{
header("Location: previous.html");
die();
}

if(isset($_POST['next']))
{
header("Location: next.html");
die();

}
 10
Author: Samuel Mugisha,
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
2014-03-03 06:16:35

De https://html.spec.whatwg.org/multipage/forms.html#implicit-submission

El botón predeterminado de un elemento de formulario es el primer botón de envío en el árbol orden cuyo propietario de formulario es ese elemento de formulario.

Si el agente de usuario admite permitir que el usuario envíe un formulario implícitamente (por ejemplo, en algunas plataformas pulsando la tecla" enter " mientras un texto campo está enfocado implícitamente envía el formulario)...

Teniendo la siguiente entrada type = "submit" y cambiar la entrada anterior a type = "button" debería dar el comportamiento predeterminado deseado.

<form>
   <input type="text" name="field1" /> <!-- put your cursor in this field and press Enter -->

   <input type="button" name="prev" value="Previous Page" /> <!-- This is the button that will submit -->
   <input type="submit" name="next" value="Next Page" /> <!-- But this is the button that I WANT to submit -->
</form>
 10
Author: nikkypx,
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-03-28 21:05:52

La primera vez que me topé con esto se me ocurrió un hack onclick()/js cuando las opciones no son prev/next que todavía me gusta por su simplicidad. Dice así:

@model myApp.Models.myModel    

<script type="text/javascript">
    function doOperation(op) {
        document.getElementById("OperationId").innerText = op;
        // you could also use Ajax to reference the element.
    }
</script>

<form>
  <input type="text" id = "TextFieldId" name="TextField" value="" />
  <input type="hidden" id="OperationId" name="Operation" value="" />
  <input type="submit" name="write" value="Write" onclick='doOperation("Write")'/>
  <input type="submit" name="read" value="Read" onclick='doOperation("Read")'/>
</form>

Cuando se hace clic en cualquiera de los botones de envío, almacena la operación deseada en un campo oculto (que es un campo de cadena incluido en el modelo al que se asocia el formulario) y envía el formulario al Controlador, que es quien decide. En el Controlador, simplemente escribe:

// Do operation according to which submit button was clicked
// based on the contents of the hidden Operation field.
if (myModel.Operation == "Read")
{
     // do read logic
}
else if (myModel.Operation == "Write")
{
     // do write logic
}
else
{
     // do error logic
}

También puedes apretar esto ligeramente usando códigos de operación numéricos para evitar el análisis de cadenas, pero a menos que juegue con Enumeraciones, el código es menos legible, modificable y auto-documentable y el análisis es trivial, de todos modos.

 10
Author: MiddleAgedMutantNinjaProgrammer,
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-09-03 13:37:04

Me encontré con esta pregunta al tratar de encontrar una respuesta a básicamente la misma cosa, solo que con asp.net controles, cuando me di cuenta de que el botón asp tiene una propiedad llamada UseSubmitBehavior que le permite establecer cuál hace el envío.

<asp:Button runat="server" ID="SumbitButton" UseSubmitBehavior="False" Text="Submit" />

Solo en caso de que alguien esté buscando el asp.net forma del botón de hacerlo.

 8
Author: Barry Franklin,
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-24 17:29:22

Con javascript (aquí jQuery), puede desactivar el botón prev antes de enviar el formulario.

$('form').on('keypress', function(event) {
    if (event.which == 13) {
        $('input[name="prev"]').prop('type', 'button');
    }
});
 7
Author: GuillaumeS,
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-08-14 10:01:14

Resolví un problema muy similar de esta manera:

  1. Si javascript está habilitado (en la mayoría de los casos hoy en día), entonces todos los botones de envío son " degradados" a botones al cargar la página a través de javascript (jquery). Eventos de clic en el botón" degradado " los botones escritos también se manejan a través de javascript.

  2. Si javascript no está habilitado, el formulario se sirve al navegador con varios botones de envío. En este caso, al presionar enter en un textfield dentro del formulario, se enviará el formulario con el primer botón en lugar del deseado predeterminado , pero al menos el formulario sigue siendo utilizable: puede enviar con los botones prev y next .

Ejemplo de trabajo:

<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </head>
    <body>
    <form action="http://httpbin.org/post" method="post">
    If javascript is disabled, then you CAN submit the form with button1, button2 or button3.
    If you press enter on a text field, then the form is submitted with the first submit button.

    If javascript is enabled, then the submit typed buttons without the 'defaultSubmitButton'
    style are converted to button typed buttons.

    If you press enter on a text field, then the form is submitted with the only submit button
    (the one with class defaultSubmitButton)
    If you click on any other button in the form, then the form is submitted with that button's
    value.
    <br />
    <input type="text" name="text1" ></input>
    <button type="submit" name="action" value="button1" >button 1</button>
    <br />
    <input type="text" name="text2" ></input>
    <button type="submit" name="action" value="button2" >button 2</button>
    <br />
    <input type="text" name="text3" ></input>
    <button class="defaultSubmitButton" type="submit" name="action" value="button3" >default button</button>
    </form>
    <script>
    $(document).ready(function(){

    /* change submit typed buttons without the 'defaultSubmitButton' style to button typed buttons */
    $('form button[type=submit]').not('.defaultSubmitButton').each(function(){
        $(this).attr('type', 'button');
    });

    /* clicking on button typed buttons results in:
       1. setting the form's submit button's value to the clicked button's value,
       2. clicking on the form's submit button */
    $('form button[type=button]').click(function( event ){
        var form = event.target.closest('form');
        var submit = $("button[type='submit']",form).first();
        submit.val(event.target.value);
        submit.click();
    });

    });
    </script>
    </body>
    </html>
 0
Author: riskop,
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-03-06 10:32:08

Prueba esto..!

<form>
  <input type="text" name="Name" />
  <!-- Enter the value -->

  <input type="button" name="prev" value="Previous Page" />
  <!-- This is the button that will submit -->
  <input type="submit" name="next" value="Next Page" />
  <!-- But this is the button that I WANT to submit -->
</form>
 0
Author: Gowtham Balusamy,
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-04-11 20:51:12

Puede usar Tabindex para resolver este problema, También cambiar el orden del botón sería una forma más eficiente de lograr esto. Cambie el orden del botón y agregue float valores para asignarles la posición deseada que desea mostrar en su vista HTML.

 0
Author: Jyoti mishra,
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-04-25 06:28:32

Usando el ejemplo que usted dio:

<form>
<input type="text" name="field1" /><!-- put your cursor in this field and press Enter -->
<input type="submit" name="prev" value="Previous Page" /> <!-- This is the button that will submit -->
<input type="submit" name="next" value="Next Page" /> <!-- But this is the button that I WANT to submit -->
</form>

Si hace clic en "Página anterior" solo se enviará el valor de "anterior". Si hace clic en "Página siguiente" solo se enviará el valor de "siguiente".

Sin embargo, si presiona enter en algún lugar del formulario, ni "prev" ni "next" serán enviados.

Así que usando pseudo código podrías hacer lo siguiente:

If "prev" submitted then
    Previous Page was click
Else If "next" submitted then
    Next Page was click
Else
    No button was click
 -3
Author: GateKiller,
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
2008-08-05 15:08:42