2013-02-13 49 views
0

我有一個有很多小的單行表單的頁面,每個表單都有5個項目。這些表單具有id form1,form2,form3等,並且項目的id和submit按鈕遵循相同的模式。我已經寫出了以下用於處理表單的ajax腳本,其中變量$ n對應於表單和項目編號。我不確定的是如何循環瀏覽頁面上每個表單的腳本。我是否需要先計算頁面上的表單數量,然後創建一個循環,如果有的話,我該怎麼做?通過ajax腳本循環處理頁面上的表格

$(".submit$n").click(function() { 

     var action = $("#form$n").attr('action'); 
     var form_data = { 
      name: $j("#name$n").val(), 
      date: $j("#date$n").val(), 
      attended: $j("#attended$n").val(), 
      paid: $j("#paid$n").val(), 
      method: $j("#method$n").val(), 
      is_ajax: 1 
     }; 

     $j.ajax({ 
      type: "POST", 
      url: action, 
      data: form_data, 
      success: function(response){ 

       if(response == 'success') 

        $j("#form$n").fadeOut(800); 
        console.log(response); 
      } 
     }); 

     return false; 
    }); 

}); 

回答

1

我很抱歉,但我不認爲這是被正確設置,並且接受的答案也不是這樣,它只是非常混亂。我不確定您的原始代碼是否已複製到您擁有的每種表格中(因爲整個$n可變的東西會讓我感到困惑,並讓我覺得您已經有好幾次了),但如果是這樣,則不需要。這就是我會用的:

$(document).ready(function() { 
    $(".submit").click(function() { 
     var $this = $(this); 
     var $form = $this.closest("form"); 
     var action = $form.attr('action'); 

     var form_data = { 
      name: $form.find("[id^=name]").val(), 
      date: $form.find("[id^=date]").val(), 
      attended: $form.find("[id^=attended]").val(), 
      paid: $form.find("[id^=paid]").val(), 
      method: $form.find("[id^=method]").val(), 
      is_ajax: 1 
     }; 

     $.ajax({ 
      type: "POST", 
      url: action, 
      data: form_data, 
      success: function (response) { 
       if (response == 'success') { 
        $form.fadeOut(800); 
       } 
       console.log(response); 
      } 
     }); 

     return false; 
    }); 
}); 

只要給所有的提交按鈕一個「提交」類,這應該工作正常。只是爲了確保,你的HTML將有這樣的格式:

<form id="form1" action="page1.php"> 
    <input type="text" id="name1" name="name1" /><br /> 
    <input type="text" id="date1" name="date1" /><br /> 
    <input type="text" id="attended1" name="attended1" /><br /> 
    <input type="text" id="paid1" name="paid1" /><br /> 
    <input type="text" id="method1" name="method1" /><br /> 
    <input type="submit" class="submit" value="Submit" /> 
</form> 

只要你明白髮生了什麼,JavaScript的發現提交按鈕的父窗體單擊時。然後,用這種形式,它發現有一個id屬性與「名稱」,「日期」等啓動你可以做到這一點,因爲你已經清楚地分離控制到自己的形式所有後代。所以用這個代碼,你可以放心,當你點擊提交按鈕,你抓住所有的控件的值從它的形式。

+0

謝謝伊恩。這很好。 – Nick 2013-02-14 23:02:09

0

添加一個公共類,你所有的提交按鈕,如:<input type="submit" id="submit1" name="submit1" class="submit" />

然後更改您的代碼:

$('.submit').on('click', function() { 
    var n = this.id.substr(6); 
    // n is the number of the form. 6 because the word submit has 6 characters. 
    // You might want to do this some other way. 

    // you can get the rest of the values by doing 
    $('#name' + n).val() 
    // and so on 
}); 
+0

謝謝,這是行之有效的。 – Nick 2013-02-13 23:23:43