2011-09-06 114 views
2

我有以下代碼。我想向數組添加/刪除複選框值並傳遞給JavaScript ajax調用。我希望能夠將所有排序數組傳遞給ajax調用的數組。每次更改一個複選框時,它都會更新數組,這又會更新傳遞給ajax的數組。多維複選框組值的多維數組jQuery post數組AJAX

<input class='sort1' type='checkbox' value='' name='sort1' /> 
<input class='sort1' type='checkbox' value='' name='sort1' /> 
<input class='sort1' type='checkbox' value='' name='sort1' /> 

<input class='sort2' type='checkbox' value='' name='sort2' /> 
<input class='sort2' type='checkbox' value='' name='sort2' /> 

<input class='sort3' type='checkbox' value='' name='sort3' /> 
<input class='sort3' type='checkbox' value='' name='sort3' /> 
<input class='sort3' type='checkbox' value='' name='sort3' /> 
<input class='sort3' type='checkbox' value='' name='sort3' /> 


var arr_sort = {} 
var arr_sort1 = {}; 
var arr_sort2 = {}; 
var arr_sort3 = {}; 

    $(".sort1").delegate("input[type='checkbox']", 'change', function() { 
     var $this = $(this); 

     if ($this.prop('checked')) { 
      arr_sort1[$this.attr('name')] = $this.val(); 
     } else { 
      delete arr_sort1[$this.attr('name')]; 
     } 

     ajax_call(); 

    }); 

$(".sort2").delegate("input[type='checkbox']", 'change', function() { 
     var $this = $(this); 

     if ($this.prop('checked')) { 
      arr_sort2[$this.attr('name')] = $this.val(); 
     } else { 
      delete arr_sort2[$this.attr('name')]; 
     } 

     ajax_call(); 

    }); 

$(".sort3").delegate("input[type='checkbox']", 'change', function() { 
     var $this = $(this); 

     if ($this.prop('checked')) { 
      arr_sort3[$this.attr('name')] = $this.val(); 
     } else { 
      delete arr_sort3[$this.attr('name')]; 
     } 

     ajax_call(); 

    }); 

function ajax_call(){ 

    $.ajax({ 
     type: 'POST', 
     url: "file.php", 
     data: { thisaction: thisaction, sort: arr_sort}, 
     success: function(data){ 
      $("#results").html(data); 
      } 
     }); 

} 

我也許可以做到這一點,但我想通過數組PHP來處理,特別是如果有更多的複選框組添加。

成果

array (
    "sort1" => array("1","2","3"), 
    "sort2" => array("this","that"), 
    "sort3" => array("other","ok") 
) 

or 

array (
    "sort1" => array("1","2","3"), 
    "sort2" => array("this") 
    "sort3" => array() 
) 
+0

你能否提出更具體的問題?我不明白你在問什麼。 – nnnnnn

回答

0

答:http://jsfiddle.net/morrison/XS48K/

注:

  • 每個name必須是唯一的。無論如何,這是一個很好的形式。我將它們命名爲box#,但您應該使用更合適的名稱來描述它們的內容。使用data屬性來分組對象。這是執行此操作的語義方式。
  • 您的input s應該在form標籤id這可以幫助您使用jQuery選擇器來獲取所需的對象。
  • 我刪除了value屬性。如果您願意,您可以重新輸入價值。我只是不希望看到那裏的值屬性。
  • 您應該將它們全部存儲在對象或數組中。這樣就可以在一個地方管理所有已選狀態。
+0

@nnnnnn,你需要知道**刪除**不要從數組中刪除一個元素,它只會將它設置爲undefined,所以你可以得到像'group1:{box1:undefined,box2:undefined,box3: undefined}' – atma

+0

得到這個錯誤$ this.prop不是函數 [Break On This Error] if($ this.prop('checked')){ – madphp

+0

.prop()僅在jQuery 1.6中引入 – atma