Get only checked element from getElementsByName() in Javascript?
37,257
Solution 1
Just filter for the elements which are checked:
var choices = [];
var els = document.getElementsByName('choice_shrd_with_me');
for (var i=0;i<els.length;i++){
if ( els[i].checked ) {
choices.push(els[i].value);
}
}
Solution 2
For IE < 9
function getCheckedByName(name){
var chks = document.getElementsByName(name);
var results = [];
for(var i = 0; i < chks.length; i++){
chks[i].checked ? results.push(chks[i]):"";
}
return results;
}
For Modern Browsers
function getModernCheckedByName(name){
return Array.prototype.slice.call(document.getElementsByName(name)).filter(function(e){
return e.checked;
});
}
Working Example
Solution 3
For a vanilla js solution that doesn't require a loop use querySelectorAll
const choices = document.querySelectorAll("input[name='choice_shard_with_me']:checked")
Solution 4
The JQuery version of it is quite slick:
var choices = [];
$("input[name='choice_shard_with_me']:checked").each(function() {
choices.push($(this).attr('value'));
});
:checked (with quite similar example of what you want to accomplish)
Related videos on Youtube
Comments
-
pynovice almost 3 years
I have a HTML like this:
<input type="checkbox" name="choice_shrd_with_me" id="choice{{ forloop.counter }}" value="{{ choice.file_name }}" />
I am trying to get only the checked elements in array like this in Javascript:
var choices = []; for (var i=0;i<document.getElementsByName('choice_shrd_with_me').length;i++){ choices.push(document.getElementsByName("choice_shrd_with_me")[i].value); }
The above gets all the values whether the checkbox is checked or not. I want to get only the values on which checkbox is checked. How can I do that?
-
Felix Kling almost 11 yearsJust FIY, when working with
NodeList
s , it makes sense to cache the length. Because the list gets reevaluated (since it is live) whenever you access.length
. -
pynovice almost 11 yearsThanks for your answer @Sirko. I will accept your answer whenever I can.