Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

jquery - 使用jquery检查/取消选中复选框? [重复](check / uncheck checkbox using jquery? [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

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

(我的页面中有一些输入文本字段,并使用JavaScript显示其值。)

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

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

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

(在这里,我想检查如果value == 1 ,则应选中此复选框。)

Otherwise, it should remain unchecked.

(否则,它应该保持未选中状态。)

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

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

if(value == 1) {
    $('#uncheck').hide();
    $('#check').show();
} else{
    $('#uncheck').show();
    $('#check').hide();
}
  ask by Irfan Ahmed translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For jQuery 1.6+ :

(对于jQuery 1.6+:)

.attr() is deprecated for properties;

(.attr()已弃用于属性;)

use the new .prop() function instead as:

(使用新的.prop()函数代替:)

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

For jQuery < 1.6:

(对于jQuery <1.6:)

To check/uncheck a checkbox, use the attribute checked and alter that.

(要检查/取消选中复选框,使用属性checked和改变这一点。)

With jQuery you can do:

(使用jQuery,您可以:)

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

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

(因为你知道,在HTML中,它看起来像:)

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

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to).

(但是,您无法信任.attr()方法来获取复选框的值(如果需要)。)

You will have to rely in the .prop() method.

(您将不得不依赖.prop()方法。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...