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
637 views
in Technique[技术] by (71.8m points)

jquery - .attr('checked','checked') does not work

I am trying to check radio. Neither the following works:

[edit]

$('selector').attr('checked','checked');
$('selector').attr('checked',true);

The two alert() in the following code show "1" and "a", respectively. My expectation is the second alert() showing "b".

Opera does check the second radio box in its browser, but its element inspector, dragonfly, shows that the DOM is not changed.

[end edit]

I had read the FAQ before I posted this question:

http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_check.2Funcheck_a_checkbox_input_or_radio_button.3F

Helps will be much appreciated!

TIA

The xhtml page and code follows:

<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Weird Behavior</title>
<script type="text/javascript" src="scripts/jquery.js"/>
<script type="text/javascript">
function clickme(){
    alert($('input[name="myname"][value="b"]').length);
    $('input[name="myname"][value="b"]').attr('checked','checked');
    $('#b').attr('checked',true);
    alert($('input[name="myname"][checked]').val());
};
</script>
</head>
<body>
    <form action="">
        <fieldset>
            <legend>Why check is not switched?</legend>
            <input type="radio" name="myname" value="a" id="a" checked="checked"/>A
            <input type="radio" name="myname" value="b" id="b"/>B
        </fieldset>
    </form>
    <p>
    <button type="button" onclick="clickme()">click me</button>
    </p>
</body>
</html>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
 $('.checkbox').attr('checked',true);

will not work with from jQuery 1.6.

Instead use

$('.checkbox').prop('checked',true);
$('.checkbox').prop('checked',false);

Full explanation / examples and demo can be found in the jQuery API Documentation https://api.jquery.com/attr/


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

...