Reputation: 4867
Perhaps it is very basic, but I have some issue with the radios.length property. I have some input like so :
<input type="radio" name="name1" value="test1" checked='checked'/><br />
<input type="radio" name="name2" value="test2" checked='checked'/><br />
When I alert the radios.length property, I always have 0 as an answer. Could someone explain why ?
Upvotes: 0
Views: 2317
Reputation: 55750
radios.length is not a valid property in the DOM.. You need to find those(which are input in this case) and then use the length property on it ..
var radios = document.getElementsByTagName("input") ;
alert(radios.length) // this will alert the correct value
UPDATE
To Select only the Radio buttons you can do this
var radios = document.getElementsByTagName("input") ;
var checkBoxes = [];
for(var i =0, len = radios.length; i< len;i++){
if(radios[i].type === 'radio'){
checkBoxes.push(radios[i]);
}
};
console.log(checkBoxes)
Also if you are using jQuery do not forget to encase your script in DOM Ready handler
jQuery
$('#radio1').attr('type') // Need to use the .attr() method
Upvotes: 1
Reputation: 4457
You can also use document.querySelectorAll(). It allows to retrieve elements by css selector and is supported by all major browsers, including IE >= 8.
document.querySelectorAll('input[type=radio]').length
https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll
Upvotes: 1
Reputation: 39929
radios
is not a valid object in the browser. You need to search the DOM for the inputs
.
Using jQuery:
$("input[type=radio]").length
would give you 2
In raw javascript, you could do something like:
document.getElementsByTagName("input")
But this would give you ALL <input>
elements.
Upvotes: 1