2012-06-19 75 views
0

要澄清我得到的CHECKKBOXES的值。我需要將它們組織成一個陣列,類似於PHP示例。感謝把選中的複選框放到數組中

我想建立一個選中的複選框數組通過AJAX進行處理的PHP。最初我通過PHP獲得了選中的複選框,但我無法將此過程轉換爲Javascript。

有三種不同的複選框組('第一','第二','第三'),並且對於這些組中的每個組,都有4個不同的複選框可以檢查。

複選框以下的HTML中相同的圖案到值4

<input type="checkbox" name="first" class="selection first" value="1" /> 
<input type="checkbox" name="second" class="selection second" value="1" /> 
<input type="checkbox" name="third" class="selection third" value="1" /> 
<input type="checkbox" name="first" class="selection first" value="2" /> 
<input type="checkbox" name="second" class="selection second" value="2" /> 
<input type="checkbox" name="third" class="selection third" value="2" /> 

等....

PHP代碼將返回選中的複選框等這樣的陣列。

$selections => array(
['first'] => array(
[0] => 1, 
[1] => 3, 
[2] => 4), 
['second'] => array(
[0] => 2), 
['third'] => array(
[0] => 1, 
[1] => 4) 
); 

我一直在努力,試圖在JavaScript中複製,但我不斷收到錯誤,如cannot convert undefined to object和喜歡。我循環可用的位置來創建數組,然後循環所有的複選框,如果選中,我得到的價值。

console.log()打印位置('第一','第二'或'第三')和選擇編號(1 - 4)。這就是我需要的,但是我怎麼把它放在類似於PHP的數組中呢?

function getSelections() { 

var selections = new Array(); 

$('.position').each(function() { 
    selections[$(this).attr('value')] = new Array; 
}); 

$('.selection').each(function() { 
    if($(this).prop('checked') == true) { 
     position = $(this).attr('name'); 
     selection = $(this).attr('value'); 

     console.log(position + ' - ' + selection); 
    } 
}); 
return selections; 

}

它被髮送到一個PHP腳本作爲JSON,我需要它像一個PHP數組進行解碼。

+0

搜索jQuery的複選框ABD你會發現像十個重複的問題.. – rlemon

+0

我不是問如何得到選定的複選框,如果你看到的問題,你會發現我已經得到了選定的值,我正在尋找如何將它們放入類似於php的一個數組中 – CrazyCrisUk

回答

1

沒什麼特別的需要....改變這一點,並查看張貼的陣列。

<input type="checkbox" name="first[]" class="selection first" value="1" /> 
<input type="checkbox" name="second[]" class="selection second" value="1" /> 
<input type="checkbox" name="third[]" class="selection third" value="1" /> 
<input type="checkbox" name="first[]" class="selection first" value="2" /> 
<input type="checkbox" name="second[]" class="selection second" value="2" /> 
<input type="checkbox" name="third[]" class="selection third" value="2" /> 

然後序列化這是正常的,通過ajax代替提交。

+0

這就是我如何用PHP來處理它,不知道它會與JS一起工作。我會嘗試序列化,並讓你知道它是否有效!非常感謝! – CrazyCrisUk

+0

值現在在阿賈克斯!感謝您的幫助! – CrazyCrisUk

+2

今天的課......從來沒有試圖讓它變得比它需要的複雜!先嚐試簡單的事情:) – Brian