view raw
Masao Liu Masao Liu - 1 year ago 46
Javascript Question

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

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



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:

Helps will be much appreciated!


The xhtml page and code follows:

<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="" xml:lang="en" lang="en">
<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(){
<form action="">
<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
<button type="button" onclick="clickme()">click me</button>


With jQuery, never use inline onclick javascript. Keep it unobtrusive. Do this instead, and remove the onclick completely.

Also, note the use of the :checked pseudo selector in the last line. The reason for this is because once the page is loaded, the html and the actual state of the form element can be different. Open a web inspector and you can click on the other radio button and the HTML will still show the first one is checked. The :checked selector instead filters elements that are actually checked, regardless of what the html started as.

$('button').click(function() {