javascript - 使用 Jquery 设置复选框

标签 javascript jquery checkbox

我有一个动态表单,其中有许多复选框。我想创建一个“全选”方法,单击该方法时会自动检查表单中的所有框。

[x] select all //<input type="checkbox" id="select-all"> Select all

[] item 1 //<input type="checkbox" id="1" class="checkbox1" value="1">
[] item 2 //<input type="checkbox" id="2" class="checkbox1" value="2">

[submit]

我的 jQuery 如下:

$(document).ready(function(){
    $('#select-all').click(function() {
        if (this.checked)
        {
        console.log("Check detected");

        $('.checkbox1').each(function() {
            console.log('Checking the item with value:' + this.value );
            $(this).prop('checked', true);
            console.log(this);

        });

    } else {
        console.log("not checked");
    }
});

});

我的控制台输出:

> Check detected
> Checking the item with value:1
> <input type=​"checkbox" id=​"1" class=​"checkbox1" value=​"1">​
> Checking the item with value:2
> <input type=​"checkbox" id=​"2" class=​"checkbox1" value=​"2">​

我可以循环遍历每个项目,但是,我不确定如何实际将复选框设置为选中。

我正在努力解决的部分是检查状态的实际设置,我知道我需要使用: .prop('checked',true) 但是,我对实际元素使用什么? $(this) 显然不起作用...

$(this).prop('checked', true);

最佳答案

使用这个简单的代码

$(".checkAll").change(function(){
    $('.checkbox1').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Check all</label>
<input type="checkbox" class="checkAll" />

<br/><br/>
<input type="checkbox" class="checkbox1" />
<input type="checkbox" class="checkbox1" />
<input type="checkbox" class="checkbox1" />
<input type="checkbox" class="checkbox1" />

关于javascript - 使用 Jquery 设置复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38028792/

相关文章:

javascript - react 点击计数器 : Updating State of just one element

javascript - 包含可拖动的圆圈到更大的圆圈

javascript - 甜蜜页面 jquery 上一个/下一个按钮

php - jQuery 在选中某一项时取消选中除一项之外的所有项

javascript - Javascript 中的内容偏移量

javascript - 从元素的样式中定位多个元素

javascript - 将表单的复选框值作为 JSON 传递?

c# - asp.net 选择所有/无复选框

c# - 单击 HTML 按钮调用服务器端功能

jquery - 表单序列化不起作用