2012-03-30 16 views

Odpowiedz

27

Z jQuery można powiązać wywołanie zwrotne z zdarzeniem submit przy pomocy metody .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"); 
    } 
}); 

Wskazówka: Aby upewnić się, że wszystkie elementy można znaleźć powinno być umieszczone w domready funkcji.

+0

można wyjaśnić Wskazówka: Komunikat więcej ? Mówisz, że musisz zawinąć całą rzecz w: $ (document) .ready (function() {YOURCODEHERE}); – tgharold

+0

@tgharold Nie, ponieważ nie jest to związane z pytaniem. Całość dokładnie wyjaśnia w dostarczonym łączu. – mekwall

2

zwykły DOM (brak biblioteki), twój HTML będzie wyglądać mniej więcej tak:

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

i twój scenariusz będzie wyglądał mniej więcej tak:

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'; 
    }; 
Powiązane problemy