I have radio buttons in HTML like this:
<td>
<input id="radio1" type="radio" name="correctAnswer" value="1">1</input>
<input id="radio2" type="radio" name="correctAnswer" value="2">2</input>
<input id="radio3" type="radio" name="correctAnswer" value="3">3</input>
<input id="radio4" type="radio" name="correctAnswer" value="4">4</input>
</td>
This is in a form tag, and when user submits a form I want to make all the radio buttons back to the default. Meaning none of them checked.
I have this code but it gives an error saying [0] is null or not an object
$('input[@name="correctAnswer"]')[0].checked = false;
$('input[@name="correctAnswer"]')[1].checked = false;
$('input[@name="correctAnswer"]')[2].checked = false;
$('input[@name="correctAnswer"]')[3].checked = false;
I am doing this in IE 6.
In versions of jQuery before 1.6 use:
In versions of jQuery after 1.6 you should use:
but if you are using 1.6.1+ you can use the first form (see note 2 below).
Note 1: it is important that the second argument be false and not "false" since "false" is not a falsy value. i.e.
Note 2: As of jQuery 1.6.0, there are now two similar methods,
.attrand.propthat do two related but slightly different things. If in this particular case, the advice provide above works if you use 1.6.1+. The above will not work with 1.6.0, if you are using 1.6.0, you should upgrade. If you want the details, keep reading.Details: When working with straight HTML DOM elements, there are properties attached to the DOM element (
checked,type,value, etc) which provide an interface to the running state of the HTML page. There is also the.getAttribute/.setAttributeinterface which provides access to the HTML Attribute values as provided in the HTML. Before 1.6 jQuery blurred the distinction by providing one method,.attr, to access both types of values. jQuery 1.6+ provides two methods,.attrand.propto get distinguish between these situations..propallows you to set a property on a DOM element, while.attrallows you to set an HTML attribute value. If you are working with plain DOM and set the checked property,elem.checked, totrueorfalseyou change the running value (what the user sees) and the value returned tracks the on page state.elem.getAttribute('checked')however only returns the initial state (and returns'checked'orundefineddepending on the initial state from the HTML). In 1.6.1+ using.attr('checked', false)does bothelem.removeAttribute('checked')andelem.checked = falsesince the change caused a lot of backwards compatibility issues and it can’t really tell if you wanted to set the HTML attribute or the DOM property. See more information in the documentation for .prop.