How to select and pick values from all checkboxes with the checked property?

3

I noticed that "selecting all checkboxes with the .checked property checked is a very recurring question in web development, so I'll post a solution here using Jquery .

sub>

How to select and pick values from all checkboxes with the checked property checked?

    
asked by anonymous 14.06.2016 / 22:12

2 answers

5

You can use the pseudo-selector :checked that is part of the W3C specification. Natively, without recourse to libraries.

Using document.querySelectorAll('input:checked'); you get a list of the elements that are marked.

In your code you could use this way:

var confirma = document.getElementById('confirma');
var resultado = document.getElementById('resultado');
confirma.addEventListener('click', function() {
    var checkados = document.querySelectorAll('input:checked');
    resultado.innerHTML = [].map.call(checkados, function(el){
    return el.value;
    }).join(', ');
});

jsFiddle: link

If you want to use the jQuery API for example you can do so, also using :checked but jQuery :

$('#confirma').on('click', function() {
    var valores = $('input:checked').map(function() {
        return this.value;
    }).get().join(', ');
    $('#resultado').html(valores);
});

jsFiddle: link

    
14.06.2016 / 23:56
5

As in the example, I'll get the value property of checked checkboxes when I click the button and insert inside the <div id="resultado"> on the page.

Considering the checkbox inputs:

$('#confirma').click(function() {

  $("input:checked").each(function() {

    $('#resultado').append($(this).attr("value"));
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox" value="check1" name="c1">
<label for="c1">Primeiro check</label>

<input type="checkbox" value="check2" name="c2">
<label for="c2">Segundo Check</label>

<input type="checkbox" value="check3" name="c3">
<label for="c3">Terceiro Check</label>

<button id="confirma">Confirma</button>


<div id="resultado"></div>

I tried to be as simple and objective as possible. Any suggestion or improvement is welcome :). Hope it helps.

    
14.06.2016 / 22:12