I have a form with about 25 checkbox's

I need to ensure at least one is selected, how can I do this with so many checkbox's?

    Use either a commonality in the naming scheme (either of the 'name' or 'id' attributes) or use DOM methods on a common parent node to iterate over all of the checkboxes. Stop at the first one you find that is checked. If the loop terminates and you never found one, your condition wasn't met.

      jQuery approach:

      var hasChecked = $('input[type=checkbox]:checked').length > 0;
      

        I suppose you could also do something similar without jQuery using XPath... although I do like the brevity of the jQuery syntax in this case.

          bradgrafelman;11023971 wrote:

          I suppose you could also do something similar without jQuery using XPath... although I do like the brevity of the jQuery syntax in this case.

          The DOM/XPath version is about three times longer...

          var hasChecked = document.evaluate('.//input[@type="checkbox"][@checked]',
                           document, null, XPathResult.BOOLEAN_TYPE, null).booleanValue;

          If you're otherwise using jQuery there's no reason not to use it for this, but if you're not otherwise using jQuery it's a bit much.

            Weedpacket;11023979 wrote:

            The DOM/XPath version is about three times longer...

            ... unless, of course, your website has no other use of jQuery, in which case I would say the DOM/XPath version (or even the simplistic approach I proposed above) is several orders of magnitudes smaller when compared with (the above jQuery statement + the jQuery library). :p

            @: Moral of the story: There's more than one way to skin a mongoose. (Actually, there are three...)

              I agree, if this is the only thing you use jQuery on its not necessary to include the whole library for something like simple. However, personally I have lots of jQuery all throughout sites I've worked on, so I'm just used to doing it all in jQuery.

                Write a Reply...