Validating Radio Buttons Without a Loop

All of the prior solutions to validating radio buttons have used a loop to perform the actual validation - looping over all of the buttons in the group. Where the prior solutions have differed from one another is in how the code gets called and how it is actually attached to the radio buttons in your form. These loop variants were appropriate up until about 2011 at which time a better way became available that doesn't use a loop at all.

With this new variant on validating radio buttons, how you actually attach and call the code is not what has changed. What I have changed with this new radio button validation code is to change the way that the validation is done to get rid of the loop. By combining a few modern JavaScript method calls together we can create a single command that returns true or false depending on whether or not any of the buttons in a specified radio button group has been selected.

We do need one variable in the middle of the statement to identify the name of the radio button group to be tested and so it is still worth wrapping the single statement inside of a function so as to make it easier to run the command with the correct name.

var radioValidate = function(nam) {
return [].some.call(document.getElementsByName(nam), function(a) {return a.checked;});
}

You simply call this function passing in the name of the radio button group to be tested and the function will return true if the radio button group is valid and false if no button in the group is selected. Instead of having to loop over all the elements in the nodelist we instead simply convert the nodelist to an array and then use the Array some() method to test if the group is valid.

All modern browsers now support this method for arrays. If you need to support older browsers that do not support this method then the solution is not to go back to using a loop but instead to provide a polyfill for the method that gets used only for older browsers that don't understand modern JavaScript - that way once these antiquated browsers finally cease to be used you can simply delete the polyfill without having to rewrite your code to modernise it.

Note that an even shorter solution is available by making a !!document.querySelector("[name='"+nam+"']:checked") call but at the time of writing this there are still a lot of people using antiquated versions of Internet Explorer that do not support this call and there is no polyfill available.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate