2

複数選択されたチェックボックスのIDを取得したい

HTML :

<input type="checkbox" class="a" id="1">1
<input type="checkbox" class="a" id="2">2
<input type="checkbox" class="a" id="3">3
<input type="checkbox" class="a" id="4">4
<input type="checkbox" class="a" id="5">5

<input type="button" value="Button" id="button">

JS:

$("#button").live('click',function(){
    var a = document.getElementsByClassName("a");
    alert(a);
    alert(a.checked);
});

JSフィドル

4

4 に答える 4

4

idチェック済みの sを取得するには:

$('.a').filter(function(){
    return this.checked // Takes only checked checkboxes.
}).map(function(){
    return this.id // Makes an array which its elements are the ids.
}).get(); // Returns the array.

ライブデモ

w3c 仕様では、数字で始まる id は無効であることに注意してください。

ID および NAME トークンは文字 ([A-Za-z]) で始まり、その後に任意の数の文字、数字 ([0-9])、ハイフン ("-")、アンダースコア ("_") が続く場合があります、コロン (":")、およびピリオド (".")。

確認するにはcheckboxes:

livejQuery のバージョンが 1.4.4 未満でない限り使用しないでください

$("#containerId").on('click','#button', function(){
  $('.a').prop('checked', true);
});

ライブデモ

于 2012-05-29T08:57:02.477 に答える
3
$("body").on("click", "#button", function(){
    var ids = $(':checkbox.a')
        .filter(':checked')
        .map(function() {
            return this.id;
        });
    console.log(ids); // an array of ids
});

デモ

または

$("body").on("click", "#button", function(){
    var ids = $(':checkbox:checked.a')
        .map(function() {
            return this.id;
        }).toArray();
    console.log(ids); // an array of ids
});

デモ

または

$("body").on("click", "#button", function(){
    var ids = $(':checkbox.a')
        .map(function() {
            if( this.checked )
                return this.id;
        }).toArray();
    console.log(ids); // an array of ids
});

デモ

于 2012-05-29T08:55:36.053 に答える
3

ボックスをチェックするコードを誰もが投稿している理由がわかりません。

複数選択されたチェックボックスのIDを取得したい

これを行うには、次のコードを使用します。

$("#button").click(function() {
    var selected = $(".a:checked").map(function() {
        return this.id;
    }).get();
    alert(selected.join(","));
});

フィドルの例

も使用しないでくださいlive()delegate()またはより良い解決策ですが、ページの読み込み後に要素がページに追加されるon()場合にのみ必要です。#button

于 2012-05-29T09:00:47.563 に答える