明確にするために、チェックされたチェックボックスの値を取得しました。与えられたPHPの例と同様の配列でそれらを整理する必要があります。ありがとう
PHPで処理するためにAJAXを介して送信されるチェックボックスの配列を作成しようとしています。もともとPHPで選択したチェックボックスを取得しましたが、このプロセスをJavascriptに変換するのに問題があります。
チェックボックスには3つの異なるグループ(「最初」、「2番目」、「3番目」)があり、これらのグループごとに、チェックできる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番目」、「2番目」、または「3番目」)と選択番号(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のような配列としてデコードする必要があります。