2012-03-30 37 views

Trả lời

27

Với jQuery, bạn có thể liên kết gọi lại đến sự kiện gửi với phương thức .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"); 
    } 
}); 

Lưu ý: Để đảm bảo rằng tất cả các yếu tố có thể tìm thấy nó nên được đặt trong một hàm domready.

+0

bạn có thể giải thích Thông báo: Thông báo hơn ? Bạn đang nói rằng bạn cần phải quấn toàn bộ điều trong: $ (document) .ready (function() {YOURCODEHERE}); – tgharold

+0

@tgharold Không, bởi vì nó không liên quan đến câu hỏi. Toàn bộ điều giải thích kỹ lưỡng trong liên kết được cung cấp. – mekwall

2

Với DOM đơn giản (không có thư viện), HTML của bạn sẽ giống như thế:

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

Và kịch bản của bạn sẽ trông giống như thế này:

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'; 
    }; 
Các vấn đề liên quan