Devpaq
Devpaq

Reputation: 181

How to check if an input is a radio - javascript

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.

Upvotes: 3

Views: 6975

Answers (3)

Janspeed
Janspeed

Reputation: 2814

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);
   }

});

Upvotes: 3

mihaimm
mihaimm

Reputation: 521

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')

Upvotes: 5

Justin Bicknell
Justin Bicknell

Reputation: 4798

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

Upvotes: 2

Related Questions