Reputation: 181
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
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
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
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