チェックボックスにチェックした内容を別の場所にも表示する

Ads

Result

jQuery

var $c = $('input[type="checkbox"]');

$c.bind('change', function(){
    var add = '';
    $c.each(function(index, value) {
        if (this.checked){
            //チェックと同時にlabelのfor属性の値をテキストとして表示する
            add += ($('label[for="' + this.name + '"]').html() + ', ');
        }
    });
    if (add.length > 0) {
        //1個以上あるときは表示する
        add = 'チェックしたアイテム: ' + add.substring(0, add.length - 2) + '.';
    } else {
        add = 'まだチェックされてません';
    }
    //id="show"内に挿入
    $('#show').html(add);
});

html

<form method="get" action="">
    <input type="checkbox" id="list-a" name="list-a">
    <label for="list-a" class="light">list-a</label>
 
    <input type="checkbox" id="list-b" name="list-b">
    <label for="list-b" class="light">list-b</label>
 
    <input type="submit" value="Submit" />
</form>
<div id="show">まだチェックされてません</div>

via

jQuery store list of checkbox values in div | jQuery4u

タイトルとURLをコピーしました