jQueryを使用して、選択したチェックボックスの値を取得します


83

チェックボックスグループの「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/ですが、チェックボックスグループをその名前で選択する方法の例はありません。

これどうやってするの?

回答:


176

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

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

「locationthemes」という名前のチェックされたすべての入力を選択します

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

//or

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

デモ


ではVanillaJS

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

デモ


ES6 /スプレッド演算子の場合

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

デモ


5
私の友人であるあなたは命の恩人です。
Haring10 2015年

特に、コンソールログを使用するというアイデアが好きです。それをありがとう。
したがって、S

32
$('input:checkbox[name=locationthemes]:checked').each(function() 
{
   // add $(this).val() to your array
});

作業デモ

または

jQueryのis()関数を使用します。

$('input:checkbox[name=locationthemes]').each(function() 
{    
    if($(this).is(':checked'))
      alert($(this).val());
});


18

配列のマップは最も速く、最もクリーンです。

var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })

次のような配列として値を返します。

array => [2,3]

城と納屋がチェックされ、他はチェックされなかったと仮定します。


12

jqueryのmap関数を使用する

var checkboxValues = [];
$('input[name=checkboxName]:checked').map(function() {
            checkboxValues.push($(this).val());
});

この例では、checkboxNameは「locationthemes」である必要があることを理解しています
hrabinowitz 2015



2

つまり、すべてが1行になります。

var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); } ).get().join(",");

..セレクターに関する注意[id*="checkbox"]。文字列「チェックボックス」が含まれるアイテムを取得します。ここでは少し不器用ですが、.NETCheckBoxListなどから選択した値を取得しようとしている場合は非常に便利です。その場合、「チェックボックス」は、CheckBoxListコントロールに付けた名前になります。


1
これは便利です@マイク
Yii2Developer

2
var SlectedList = new Array();
$("input.yorcheckboxclass:checked").each(function() {
     SlectedList.push($(this).val());
});

1
あなたの答えとともに説明を提供してください。
ワードリ

1
var voyageId = new Array(); 
$("input[name='voyageId[]']:checked:enabled").each(function () {
   voyageId.push($(this).val());
});      

アップグレード:var voyageIds = $('input[name="voyageId[]"]:checked:enabled').map(function() {return this.value; }).get();
ウィリアム

1

ソース-詳細

jQueryを使用して選択したチェックボックスの値を取得する

次に、jQuery each()を使用して、配列内の選択されたチェックボックス値を取得するjQueryスクリプトを記述します。このjQuery関数を使用して、ループを実行し、チェックされた値を取得して配列に入れます。

<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Get Selected Checkboxes Value Using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $(".btn").click(function() {
                var locationthemes = [];
                $.each($("input[name='locationthemes']:checked"), function() {
                    locationthemes.push($(this).val());
                });
                alert("My location themes colors are: " + locationthemes.join(", "));
            });
        });
    </script>
    </head>
    <body>
        <form method="POST">
        <h3>Select your location themes:</h3>
        <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>
        <br>
        <button type="button" class="btn">Get Values</button>
    </form>
    </body>
    </html>

0

Jquery 3.3.1、ボタンクリック時にすべてのチェックボックスの値を取得する

$(document).ready(function(){
 $(".btn-submit").click(function(){
  $('.cbCheck:checkbox:checked').each(function(){
	alert($(this).val())
  });
 });			
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="vehicle1" name="vehicle1"  class="cbCheck" value="Bike">
  <label for="vehicle1"> I have a bike</label><br>
  <input type="checkbox" id="vehicle2" name="vehicle2"  class="cbCheck" value="Car">
  <label for="vehicle2"> I have a car</label><br>
  <input type="checkbox" id="vehicle3" name="vehicle3"  class="cbCheck" value="Boat">
  <label for="vehicle3"> I have a boat</label><br><br>
  <input type="submit" value="Submit" class="btn-submit">


0

それを行うためのもう少し現代的な方法:

const selectedValues = $('input[name="locationthemes"]:checked').map( function () { 
        return $(this).val(); 
    })
    .get()
    .join(', ');

最初に、指定された名前で選択されたすべてのチェックボックスを見つけ、次にjQueryのmap()がそれぞれを繰り返し処理し、コールバックを呼び出して値を取得し、チェックボックスの値を保持する新しいjQueryコレクションとして結果を返します。次に、get()を呼び出して値の配列を取得し、join()を呼び出してそれらを単一の文字列に連結します。これは定数selectedValuesに割り当てられます。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.