我有检查复选框的工作代码但只有当第一个复选框已经被选中时它才有效。你们知道为什么吗?
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);
}
}
最佳答案
你使用了错误的方法,你可以将 .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');
使用prop()
的回调,直接比较每个元素的索引
关于javascript - 根据选择字段自动检查复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34371510/