根据 select 字段自动选中复选框

Auto check checkboxes based on select field

我有检查复选框的工作代码但它只有在第一个复选框已经被选中时才有效。你们知道为什么吗?

HTML:

<p id="ullman_seats"><input class="choice" type="checkbox" name="option['option']" value="3000"> Ullman seats
    <select id="select_ullman">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>
</p>
<p id="ullman_seats_2"><input class="choice" type="checkbox" name="option['option']" value="3000"> Ullman seats</p>
<p id="ullman_seats_3"><input class="choice" type="checkbox" name="option['option']" value="3000"> Ullman seats</p>
<p id="ullman_seats_4"><input class="choice" type="checkbox" name="option['option']" value="3000"> Ullman seats</p>

jQuery(安全,因为它将在 WordPress 中实现)

jQuery('#select_ullman').change(function () {
        if (jQuery(this).val() == '2') {
            jQuery('#ullman_seats input').attr('checked', true);
            jQuery('#ullman_seats_2 input').attr('checked', true);
        }if (jQuery(this).val() == '3') {
            jQuery('#ullman_seats input').attr('checked', true);
            jQuery('#ullman_seats_2 input').attr('checked', true);
            jQuery('#ullman_seats_3 input').attr('checked', true);
        }if (jQuery(this).val() == '4') {
            jQuery('#ullman_seats input').attr('checked', true);
            jQuery('#ullman_seats_2 input').attr('checked', true);
            jQuery('#ullman_seats_3 input').attr('checked', true);
            jQuery('#ullman_seats_4 input').attr('checked', true);
        }
   }

你必须使用.prop('checked', true);

jQuery('#select_ullman').change(function () {
        if (jQuery(this).val() == '2') {
            jQuery('#ullman_seats input').prop('checked', true);
            jQuery('#ullman_seats_2 input').prop('checked', true);
        }if (jQuery(this).val() == '3') {
            jQuery('#ullman_seats input').prop('checked', true);
            jQuery('#ullman_seats_2 input').prop('checked', true);
            jQuery('#ullman_seats_3 input').prop('checked', true);
        }if (jQuery(this).val() == '4') {
            jQuery('#ullman_seats input').prop('checked', true);
            jQuery('#ullman_seats_2 input').prop('checked', true);
            jQuery('#ullman_seats_3 input').prop('checked', true);
            jQuery('#ullman_seats_4 input').prop('checked', true);
        }    }

并选中复选框

if ($('#id').is(':checked') == true) {
            //Do something
        }
        else {
            //Do something else
        } 

您使用了错误的方法,您可以将 .attr('checked', true) 更改为 .prop('checked', true) 等以使其工作,但有一种更简单的方法可以做到这一点

jQuery('#select_ullman').on('change', function() {
    $('.ullman_seats input').prop('checked', function(i, prop) {
        return i < this.value;
    }.bind(this));
}).trigger('change');

FIDDLE

使用prop()的回调,直接比较每个元素的索引