Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery - Get checkbox with specific value

I want to get checkbox with specfic value and make it checked..

I make like this

$(":checkbox").filter({"value":5}).attr("checked","true");?

and here is the html

?<input type="checkbox" name="priv"????????????????????????????? value="1"?????????????????/>
<input type="checkbox" name="priv" value="2"/>
<input type="checkbox" name="priv" value="3"/>
<input type="checkbox" name="priv" value="4"/>
<input type="checkbox" name="priv" value="5"/>
<input type="checkbox" name="priv" value="6"/>
<input type="checkbox" name="priv" value="7"/>
 <input type="checkbox" name="priv" value="8"/>?

here's a demo of the problem

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can use Attribute Equals Selector [name="value"] to get the checkboxes with particular value. Also use prop() instead of attr() as that is recommended way by jQuery doc.

Live Demo

$(":checkbox[value=4]").prop("checked","true");

or

$("input[type=checkbox][value=5]").prop("checked",true);

Description: Selects elements that have the specified attribute with a value exactly equal to a certain value, jQuery doc.

You can also do it Using attr() but prop is more appropriate for boolean properties.

$(":checkbox[value=4]").attr("checked","true");

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method, jQuery doc

Edit, asked in comments, "How would look like the answer/find-expression with complex values, like value="Smith, David"

You can enclose that kind of values like Smith, David on single quotes. You can even use character used by jQuery like #, ., $ etc, see updated fiddle here.

$("input[type=checkbox][value='#Smith, David$']").attr("checked","true");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...