jQuery en el Formulario de Envío


¿Qué tiene de malo esto?

HTML:

<form action="http://localhost:8888/bevbros/index.php/test" method="post" accept-charset="utf-8" id="cpa-form" class="forms">        
      <input type="text" name="zip" value="Zip code" id="Zip" class="required valid">      
      <input type="submit" name="Next" value="Submit" class="forms" id="1">
  </form>
[2]} jQuery:
$("#cpa-form").submit(function(e){
    e.preventDefault();
  });
Author: Manolo, 2011-06-24

9 answers

Prueba esto:

$("#cpa-form").submit(function(e){
    return false;
});
 146
Author: Jordan Brown,
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-06-24 01:10:00

Utilice la nueva sintaxis de eventos "on".

$(document).ready(function() {
  $('form').on('submit', function(e){
    // validation code here
    if(!valid) {
      e.preventDefault();
    }
  });
});

Cita: https://api.jquery.com/on /

 42
Author: scarver2,
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-02-18 13:14:21

Creo que las respuestas anteriores son todas correctas, pero eso no indica por qué el método submit no funciona.

Bueno, el método submit no funcionará si jQuery no puede obtener el elemento form, y jQuery no da ningún error al respecto. Si su script se coloca en el encabezado del documento, asegúrese de que el código se ejecuta después de DOM es listo. Entonces, $(document).ready(function () { // your code here // }); resolverá el problema.

La mejor práctica es, siempre ponga su script en la parte inferior del documento.

 11
Author: towry,
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-04-25 15:16:09
$('#cpa-form input[name="Next"]').on('click', function(e){
    e.preventDefault();
});
 5
Author: Crisalin Petrovschi,
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-08-22 12:07:38
$(document).ready(function(){
    $("#form_id").submit(function(){
        return condition;
    });
});
 3
Author: shraddha Dharmamer,
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-11-03 14:35:33

Su código está Bien solo necesita colocarlo dentro de la función ready.

$(document).ready( function() {
  $("#cpa-form").submit(function(e){
     e.preventDefault();
  });
}
 2
Author: JAi Kathuria,
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-03-27 00:45:47

OBSOLETO - esta parte está desactualizada, así que por favor no la uses.

También puede probar este código, si, por ejemplo, ha agregado formularios dinámicos más adelante. Por ejemplo, cargó una ventana asincrónica con ajax y desea enviar este formulario.

$('#cpa-form').live('submit' ,function(e){
    e.preventDefault();      
    // do something
});

UPDATE - debe usar el método jQuery on() y tratar de escuchar el DOM del documento si desea manejar contenido agregado dinámicamente.

Caso 1, versión estática: Si tiene solo unos pocos oyentes y su formulario para manejar está codificado, entonces puede escuchar directamente en "nivel de documento". No usaría los oyentes a nivel de documento, pero intentaría profundizar en el árbol de doom porque podría conducir a problemas de rendimiento (depende del tamaño de su sitio web y su contenido)

$('form#formToHandle').on('submit'... 

O

$('form#formToHandle').submit(function(e) {
    e.preventDefault();      
    // do something
});

Caso 2, versión dinámica: Si ya escucha el documento en su código, entonces esta manera sería buena para usted. Esto también funcionará para código que se añadió más tarde a través de DOM o dinámico con AJAX.

$(document).on('submit','form#formToHandle',function(){
   // do something like e.preventDefault(); 
});

O

$(document).ready(function() {
    console.log( "Ready, Document loaded!" );

    // all your other code listening to the document to load 

    $("#formToHandle").on("submit", function(){
        // do something           
    })
});

O

$(function() { // <- this is shorthand version
   console.log( "Ready, Document loaded!" );

    // all your other code listening to the document to load 

    $("#formToHandle").on("submit", function(){
        // do something           
    })
});
 1
Author: NFlows,
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-09-01 05:29:50

Esta es una pregunta antigua, pero la respuesta aceptada aquí realmente no llega a la raíz del problema.

Puede resolver esto de dos maneras. Primero con jQuery:

$(document).ready( function() { // Wait until document is fully parsed
  $("#cpa-form").on('submit', function(e){

     e.preventDefault();

  });
}

O sin jQuery:

// Gets a reference to the form element
var form = document.getElementById('cpa-form');

// Adds a listener for the "submit" event.
form.addEventListener('submit', function(e) {

  e.preventDefault();

});

No es necesario usar return false para resolver este problema.

 1
Author: Chuck Le Butt,
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-11 17:52:50

Hola buscó una solución para hacer que un formulario Ajax funcione con Google Tag Manager (GTM), la devolución de falso impidió la finalización y enviar la activación del evento en tiempo real en google analytics la solución fue cambiar la devolución de falso por e. preventDefault (); que funcionó correctamente sigue el código:

 $("#Contact-Form").submit(function(e) {
    e.preventDefault();
   ...
});
 0
Author: Navi,
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-04-25 22:09:58