0

澄清一下,我得到了选中复选框的值。我需要将它们组织成一个类似于给出的 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;

}

它将作为 JSON 发送到 PHP 脚本,我需要将其解码为像 PHP 一样的数组。

4

2 回答 2

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 提交。

于 2012-06-19T11:05:58.290 回答
0

Jquery :checked Selector可能会有所帮助

于 2012-06-19T11:04:44.440 回答