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

Asked

Viewed 1,997 times

3

I realized that "how to select all checkboxes with the property .checked marked is a very recurring question in web development, so I will post a solution here, using Jquery.

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

  • Yes, I never remember how you do it and I always turn to the Web. Good question.

2 answers

5


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

Considering the inputs of checkbox:

$('#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>

<input type="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 :) . I hope it helps.

  • 2

    (this).attr("value") there is one missing $. It could also be just this.value.

5

You can use the pseudo-selector :checked which is part of the W3C specification. Natively, no libraries.

Using document.querySelectorAll('input:checked'); You get a list of items that are marked.

In your code you could use it like this:

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: https://jsfiddle.net/2mfjkeua/

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

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

jsFiddle: https://jsfiddle.net/2mfjkeua/2/

  • Opa, thanks Sergio. I chose to do using Jquery this way because I thought it would make the code simpler, objective and didactic. Thank you for complimenting!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.