javascript - 根据选择字段自动检查复选框

标签 javascript jquery checkbox

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

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');

FIDDLE

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

关于javascript - 根据选择字段自动检查复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34371510/

相关文章:

javascript - 返回声明后的声明

jQuery - 快速点击后标签/输入中断的切换类

javascript - 单击按钮时的多重删除复选框无法按要求工作

jquery - 从 JQuery 中的 CK 编辑器文本区域获取文本

javascript - 如何从 Webix 中的弹出数据表中获取复选框的特定选择?

javascript - 使用jquery隐藏错误消息

javascript - Angular2 - 未捕获尝试使用已销毁的 View : detectChanges

javascript - 减少一组谓词函数

javascript - 为什么asp是:LinkButton server side event doesn't fire when clientClick returns true

javascript - JSPDF addHTML 不显示背景图片