Handling One Radio Button With JavaScript

Today, I discovered an issue that I have probably encountered in the past; but it’s been so long I forgot about it.

I had some JavaScript set up to select a radio button based on text input, and then update the text based on the selected radio button (it’s a TinyMCE plugin that inserts a shortcode into the WordPress visual editor).

Throughout all of the testing I performed, everything worked just fine. Today, though, someone else was testing the interface and could not get the text or the radio button to update properly.

After a bit of testing and messing around with the interface, I finally discovered that my JavaScript wasn’t recognizing the existence of the radio button on the form.

After a bit more testing, I realized that’s because only one radio button existed; and JavaScript doesn’t treat radio buttons as arrays when there’s only one instance. When I had been testing before, I had multiple radio buttons, so everything worked; but now there was only one button, so it fell over.

I solved the issue by having my PHP script generate a hidden radio button with no value if there is only one regular radio button. That way, the JavaScript treats the group of radio buttons as an array.

However, you should also be able to solve this issue with JavaScript itself if you’d prefer not to generate excess markup.

The JavaScript solution would be to check whether the length of the radio button array is defined or not. If the length is undefined, treat the radio button as a single entity rather than an array; and assign the checked attribute to it. If the length is defined, treat it as an array and loop through it to find the right value.

That code might look something like:

var f = document.forms[0]; 
if( typeof f.myRadio.length == 'undefined' && typeof f.myRadio != 'undefined' ) { 
  f.myRadio.checked = true; 
} else { 
  for( var i=0; i < f.myRadio.length; i++ ) { 
    if( f.myRadio[i].value == testValue ) { 
      f.myRadio[i].checked = true; 

I haven’t tested this code, and it’s entirely possible that there’s a better way to go about testing for the existence of the length property; but this should at least set you on the right path.