2

Actualmente para reutilizar el código de cada formulario estoy usando:

$('.formulario').submit(function(e){
            var value = $(this).val()
            e.preventDefault();
            $.post($(this).attr('action'), $(this).serialize(), function(data){
                data = JSON.parse(data);
                bootbox.alert(data.mensaje);
            });
        });

El problema es que cada botón submit tienen un value, que me servirá para identificar las secciones debido a que son varios formularios.

¿Cómo podría enviar los formularios y obtener el value del botón submit que forma parte de él?

2 respuestas 2

4

Aquí tienes un ejemplo

$('.formulario').submit(function(e){
             e.preventDefault();
            //Buscar el input de tipo submit. Ojo aqui porque puede fallar si no se controla.
            var submitValue = $(e.target).find('input[type=submit]')[0].name
             
            //Añadimos los valores. Mira serializeArray puede que te sea mas util. 
            var datos = `${$(this).serialize()}&desde=${submitValue}`
            
            $.post($(this).attr('action'), datos, function(data){
                data = JSON.parse(data);
                bootbox.alert(data.mensaje);
            });
  
          alert(datos)
    });
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

  
  <form class="formulario">
      
    <input name="usuario" />
    <input name="email" />

    <input type="submit" name="registro" value="registro" />
  </form>
  
    <form class="formulario">
      
    <input name="password" />
     <input type="submit" name="login" value="login" />

  </form>
</body>
</html>

2

Para recoger el value del botón, tendrías que hacer e.target. Target recoge el elemento que lanzó el evento, en este caso tu botón de submit. Quedaría algo como:

var value = e.target.value;

No sé cómo lo tienes montado, pero creo que igual tendría sentido darle el identificador al formulario, no al botón, y pasarle a la función del sumbit el identificador del formulario, como:

<input type="submit" value="Submit" onclick="enviarFormulario("formularioEjemplo");">

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.