1. ホーム
  2. javascript

[解決済み] 選択されたチェックボックスの値を取得するためにjQueryを使用する

2023-01-05 16:26:01

質問

チェックボックスグループ 'locationthemes' をループして、選択されたすべての値で文字列を構築したいと思います。 したがって、チェックボックス2と4が選択されたとき、結果は次のようになります: "3,8"

<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
<label for="checkbox-1">Castle</label>
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
<label for="checkbox-2">Barn</label>
<input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" />
<label for="checkbox-4">Bar</label>

ここで確認したのは http://api.jquery.com/checked-selector/ とありますが、チェックボックスグループを名前で選択する例がありません。

どうすればいいのでしょうか?

どのように解決するのですか?

jQueryでは、以下のような属性セレクタを使用するだけです。

$('input[name="locationthemes"]:checked');

という名前のチェックされた入力がすべて選択されます。

console.log($('input[name="locationthemes"]:checked').serialize());

//or

$('input[name="locationthemes"]:checked').each(function() {
   console.log(this.value);
});

デモ


バニラJS

[].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) {
   console.log(cb.value); 
});

デモ


ES6/spread演算子では

[...document.querySelectorAll('input[name="locationthemes"]:checked')]
   .forEach((cb) => console.log(cb.value));

デモ