質問

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?

役に立ちましたか?

解決

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

他のヒント

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/

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

const choices = document.querySelectorAll("input[name='choice_shard_with_me']:checked")

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()

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top