Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts

    Radio Button Validation

    Modern JavaScript makes it easy to validate a radio button group in a single statement without needing a loop.

    Here I've wrapped the statement in a function to make it shorter to call and to make sure that the name of the group to be validated gets substituted into the code in the right place.

    Code:
    function radioValidate(nam) {
    return [].slice.call(document.getElementsByName(nam)).some(function(a) {return a.checked;});
    }
    A polyfill will take care of antiquated browsers if you still need to support them.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,366
    Thanks
    11
    Thanked 590 Times in 571 Posts
    can be coded slightly simpler as

    Code:
    function radioValidate(nam) {
      return [].some.call(document.getElementsByName(nam), function(a) {return a.checked;});
    }
    if you don't need IE8, there's an even simpler/faster way to build the function as well:

    Code:
    function radioValidate(nam) {
      return !! document.querySelector("input[type='radio'][name='"+nam+"']:checked");
    }
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #3
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,091
    Thanks
    38
    Thanked 498 Times in 492 Posts
    Correct me if I'm wrong, but both of those functions return only 'true' or 'false' if a group of radio buttons has been checked
    not the actual option that has been checked. Correct?


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •