2012-03-30 21 views

Respuesta

27

Con jQuery, puede vincular una devolución de llamada al evento de envío con el método .submit().

$("form").submit(function(){ 
    // Let's find the input to check 
    var $input = $(this).find("input[name=whatever]"); 
    if (!$input.val()) { 
    // Value is falsey (i.e. null), lets set a new one 
    $input.val("whatever you want"); 
    } 
}); 

Aviso: Para asegurarse de que todos los elementos se pueden encontrar se debe colocar en una función domready.

+0

Puede explicar el Aviso: mensaje más ? ¿Estás diciendo que necesitas envolver todo en: $ (documento). Listo (función() {YOURCODEHERE}); – tgharold

+0

@tgharold No, porque no está relacionado con la pregunta. Todo el asunto está explicando a fondo en el enlace proporcionado. – mekwall

2

Con DOM normal (sin biblioteca), el código HTML se verá algo como:

<form name="foo" action="bar" method="post"> 
    <!-- or method="get" --> 
    <input name="somefield"> 
    <input type="submit" value="Submit"> 
</form> 

Y la secuencia de comandos se verá algo como esto:

var form = document.forms.foo; 
if (form && form.elements.something) 
    // I use onsubmit here for brevity. Really, you want to use a 
    // function that uses form.attachEvent or form.addEventListener 
    // based on feature detection. 
    form.onsubmit = function() { 
     // if (form.elements.foo.value.trim()) is preferable but trim() 
     // is not available everywhere. Note that jQuery has $.trim(), 
     // and most general purpose libraries include a trim(s) 
     // function. 
     if (form.elements.something.value.match(/^\s*$/))) 
      form.elements.something.value = 'DEFAULT VALUE'; 
    }; 
Cuestiones relacionadas