使用jQuery选中/取消选中复选框? [英] check / uncheck checkbox using jquery?

查看:107
本文介绍了使用jQuery选中/取消选中复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有一些输入文本字段,并且正在使用JavaScript显示它们的值.

I have some input text fields in my page and am displaying their values using JavaScript.

我正在使用.set("value","")函数编辑值,添加额外的复选框字段并传递值.

I am using .set("value","") function to edit the value, add an extra checkbox field, and to pass a value.

在这里,我要检查是否为value == 1,则应选中此复选框.否则,应保持选中状态.

Here I want to check that if value == 1, then this checkbox should be checked. Otherwise, it should remain unchecked.

我通过使用两个div来做到这一点,但是我对此感到不舒服,还有其他解决方案吗?

I did this by using two divs, but I am not feeling comfortable with that, is there any other solution?

if(value == 1) {
    $('#uncheck').hide();
    $('#check').show();
} else{
    $('#uncheck').show();
    $('#check').hide();
}

推荐答案

对于jQuery 1.6 +:

.attr()不推荐使用;使用新的 .prop()函数代替:

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

对于jQuery< 1.6:

要选中/取消选中复选框,请使用属性checked并进行更改.使用jQuery,您可以执行以下操作:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

因为您知道,在HTML中,它看起来类似于:

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

但是,您不能信任.attr()方法来获取复选框的值(如果需要).您将必须使用 .prop()方法.

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

这篇关于使用jQuery选中/取消选中复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆