[jQuery]チェックボックス問題

.propを使って解決

by tea4two

HTML

<label class="check">
    <input type="checkbox" name="check">check!</label>
<label class="check">
    <input type="checkbox" name="check">check!</label>
<label class="check">
    <input type="checkbox" name="check">check!</label>
<label class="check">
    <input type="checkbox" name="check">check!</label>
<label class="check">
    <input type="checkbox" name="check">check!</label>
    
    
<br /><br />
<label class="radio">
    <input type="radio" name="radio">check!</label>
<label class="radio">
    <input type="radio" name="radio">check!</label>
<label class="radio">
    <input type="radio" name="radio">check!</label>
<label class="radio">
    <input type="radio" name="radio">check!</label>
<label class="radio">
    <input type="radio" name="radio">check!</label>

CSS

label.active {
    background-color: lightblue;
}

JavaScript

$('.check').on('click', function () {

    $(this).toggleClass('active');
    if ($(this).hasClass('active')) {
        $(this).children('input').prop('checked', 1);
    } else {
        $(this).children('input').prop('checked', 0);
    }

    return false;

});

$('.radio').on('click', function () {
    $('.radio').removeClass('active');
    $(this).addClass('active');
    if ($(this).hasClass('active')) {
        $(this).children('input').prop('checked', 1);
    } else {
        $(this).children('input').prop('checked', 0);
    }

    return false;

});