Get only checked element from getElementsByName() in Javascript?

pynovice picture pynovice · Jul 2, 2013 · Viewed 35k times · Source

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?

Answer

Sirko picture Sirko · Jul 2, 2013

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