[snip]
Within the same form, I have 4 other sections/questions, each having a
'No Answer' checkbox. So when I used your script, and tried selecting a
'No Answer' in one section, all the other selections I had made relating
to the other questions got unchecked.
Is there an easy way to fix (and still keep everything in one form)?
It depends on the structure of your form. Assuming that all checkboxes
within a particular group share the same name, but these separate sections
use different group names (see my example), there's no problem at all.
<URL:
http://www.mlwinter.pwp.blueyonder.co.uk/clj/belly/checkboxes.html>
As I say in the comments, the current code assumes that the "No Answer"
option is the first checkbox in each group. If you place it last, you need
to uncomment the four lines prefixed with single-line comment delimiters
(//) and delete (or comment-out) the line below each of them.
The code is almost self-contained[1]. All you need to do is (repeating
some of the above):
1) Ensure that each checkbox within a group share exactly the same
name. Related checkboxes should anyway, so this shouldn't be an
issue.
2) Ensure that no two groups use the same name. Again, this
shouldn't be an issue.
3) Add the intrinsic event listener
onclick="setDefault(this);"
to each checkbox. I would have preferred using the change event,
but IE doesn't support that in the way I think it should.
The page in the URL above has been tested with:
IE6; Opera 7.54; Mozilla 1.0 and 1.73; Netscape 4.77 and 7.2;
Mozilla Firefox 0.9.3
and works as expected in all of them. I define "works" as:
1) Selecting the first checkbox in each group should uncheck all
other boxes in that group.
2) Selecting any checkbox, other than the first, should ensure that
the first box becomes unchecked.
3) Multiple checkboxes, excluding the first, can be checked at the
same time.
The commented code behaves the same way, except "first" becomes "last" in
the description above.
The final point to note in all of this is to make sure that you check the
values on the server. Don't rely solely on Javascript for validation if
you can help it.
[snipped top-post]
Hope that helps,
Mike
[1] I'd call it truly self-contained if it added the necessary event
handlers to the HTML itself, but that would be difficult without seeing
your page.