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 2 of 2
  1. #1
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,627
    Thanks
    0
    Thanked 648 Times in 638 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,298
    Thanks
    10
    Thanked 584 Times in 565 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/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%


  •  

    Posting Permissions

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