4

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?

pynovice
  • 7,424
  • 25
  • 69
  • 109

5 Answers5

6

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);
  }
}
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • Just 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`. – Felix Kling Jul 02 '13 at 09:52
  • Thanks for your answer @Sirko. I will accept your answer whenever I can. – pynovice Jul 02 '13 at 09:53
4

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

http://jsfiddle.net/yMqMf/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
2

For a vanilla js solution that doesn't require a loop use querySelectorAll

const choices = document.querySelectorAll("input[name='choice_shard_with_me']:checked")
nmase88
  • 123
  • 1
  • 4
1

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)

each()

attr()

Streamside
  • 332
  • 1
  • 8
0

Looks the solution is perfect for checkbox

but in any case if decided to change checkbox with radiobox

Simply can get the selected value of radiobox like the following :

var varName = $('input[name="formItemName"]:checked').val();  // To get selected item of your radiobox