3

How can I check if a field is a radio button?

I tried if(document.FORMNAME.FIELDNAME.type =='radio') but document.FORMNAME.FIELDNAME.type is returning undefined.

The html on the page is <input name="FIELDNAME" type="radio" value="1" > <input name="FIELDNAME" type="radio" value="0" >

Unless I am taking the whole approach wrong. My goal is to get the value of an input field, but sometimes that field is a radio button and sometimes its a hidden or text field.

Thanks.

0

3 Answers 3

5

Your example does not work because document.FORMNAME.FIELDNAME is actually an array with 2 elements (since you have 2 inputs with that name on the form). Writing if(document.FORMNAME.FIELDNAME[0].type =='radio') would work.

EDIT: Note that if you don't know if document.FORMNAME.FIELDNAME is a radio (ie you might have a text/textarea/other) it is a good idea to test if document.FORMNAME.FIELDNAME is an array first, then if the type of it's first element is 'radio'. Something like if((document.FORMNAME.FIELDNAME.length && document.FORMNAME.FIELDNAME[0].type =='radio') || document.FORMNAME.FIELDNAME.type =='radio')

Sign up to request clarification or add additional context in comments.

Comments

3

In case you don't have a form then maybe go by attribute is an option.

var elements = document.getElementsByName('nameOfMyRadiobuttons');

elements.forEach(function (item, index) {

  if (item.getAttribute("type") == 'radio') {
      var message = "Found radiobutton with value " + item.value;

      if(item.checked) {
         message += " and it is checked!"
      }

      alert(message);
   }

});

Comments

2

Your code should work, but you could try the following:

document.getElementById('idofinput').type == 'radio'

Edit: Your code doesn't work for the reason mihaimm mentions above

2 Comments

Doesn't each input of the radio group need to have its own ID?
On second thought - as long as any one of the radio inputs are a radio obviously its a radio - so my issue with unique ID didn't matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.