0

What would be the JavaScript code to check if the user has selected at least one radio button, knowing that the radio buttons all have the same "name" attribute?

Same question for checkboxes.

I do not use any fancy javascript frameworks such as JQuery and others ...

Nathan H
  • 48,033
  • 60
  • 165
  • 247
  • 2
    "I do not use any fancy javascript frameworks such as JQuery and others ...". Well, maybe you should. – SLaks Nov 11 '09 at 22:21
  • 1
    I would agree with SLaks. I would start by familiarizing myself with jQuery (or something similar) if I want to do anything dynamic apart from, say, alert('hello world!'); – theraccoonbear Nov 11 '09 at 22:22
  • See http://stackoverflow.com/questions/1682964/in-javascript-how-can-i-get-all-radio-buttons-in-the-page-with-a-given-name – Roatin Marth Nov 11 '09 at 22:23
  • 1
    Will jquery work for anyone? (that has javascript enabled of course) – Nathan H Nov 11 '09 at 22:24
  • 2
    No point is picking up a chunky library to do one trivial thing. – Quentin Nov 11 '09 at 22:24
  • @nute: Yes. jQuery will work on any browser, and is more likely to work on obscure browsers than hand-written code. (They devote lots of time to testing) – SLaks Nov 11 '09 at 22:25
  • 1
    Agreed, a proper JS library will help iron out all of the cross-browser awfulness of inconsistent DOM implementations, etc. – theraccoonbear Nov 11 '09 at 22:55
  • Thanks - I am now using jQuery – Nathan H Nov 13 '09 at 17:57

1 Answers1

1
function IsARadioButtonChecked ( radiogroup ) {
    for (var i = 0; i < radiogroup.length; i++) {
        if (radiogroup[i].checked) {
            return true;
        }
    }
    return false;
}

if (IsARadioButtonChecked(document.forms.myForm.elements.myRadioGroupName)) {
    // …
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335