简体   繁体   中英

Get only checked element from getElementsByName() in Javascript?

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/

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

对于不需要循环的 vanilla js 解决方案,请使用querySelectorAll

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM