The goal of the following bit of code is to toggle a group of radio buttons named "knowsnumberofpeople". Unfortunately, after the first message box shows up and the radio buttons change correctly, jQuery goes back and toggles everything to the original state.
Why does jQuery go back on previous items in the collection?
Code:
<script type="text/javascript">
$("input[name='numberofpeople']").change(function() {
$("input[name='knowsnumberofpeople']").each(function() {
alert("Hi there.");
if ($(this).attr("checked") === "Checked") {
$(this).attr("checked", "");
}
else {
$(this).attr("checked", "Checked");
}
}
);
}
);
</script>
Edit
To answer questions and comments...
No, the two things are different. One radio button has a textbox and the other one doesn't. Both radio buttons all have the same name. The radio buttons are named knowsnumberofpoeple and the textbox is named numberofpeople. They radio buttons have the same ID, thanks to ASP .NET MVC (I tried setting their id through htmlAttribute, didn't work out).
They go to their original state.
There are no events bound to the knowsnumberofpeople control.
Why not read the value and set it?
I tried and it doesn't work:
$("input[name='knowsnumberofpeople']").val = true;
karbassi's solution doesn't work either. It just toggles the second radio button (the one without a textbox).
More Code
<form action="/ReserveSpace/ExpectedAttendance" method="post">
<fieldset class="smallform">
<input id="knowsnumberofpeople" name="knowsnumberofpeople" type="radio" value="True" />
<input id="numberofpeople" name="numberofpeople" type="text" value="" />
<label for="numberofpeople">
(e.g. 20)</label><br />
<input checked="checked" id="knowsnumberofpeople" name="knowsnumberofpeople" type="radio" value="False" />
<label>
I'm not sure.
</label>
<p>
<input type="submit" value="Next" accesskey="N" /></p>
</fieldset>
</form>