How do I get the value of a list of ckeckboxes with jquery?

1

I've tried the following:

<input name="chklista" id="chk01" value="01" type="checkbox" />01<br />
<input name="chklista" id="chk02" value="02" type="checkbox" />02<br />
<input name="chklista" id="chk03" value="03" type="checkbox" />03<br />    
<br />
<input id="btn01" type="button" value="button" onclick="teste();" />
<br />
<br />
<div id="div01">
</div>

is in function:

function teste() {
    //não funciona
    //var chklista = $('#chklista').val();
    var chklista = $('input[name="chklista"]').val();    
    var chk01 = $('#chk01 checked').val();
    var chk02 = $('#chk02 checked').val();
    var chk03 = $('#chk03 checked').val();
    $('#div01').html("por nome: <br />chklista: " + chklista + "<br /><br />por id: <br />chk01: " + chk01 + "<br />chk02: " + chk02 + "<br />chk03: " + chk03 + "<br />");
}

The output was this:

WhenIwantedsomethinglikethis:

    
asked by anonymous 18.12.2014 / 15:11

1 answer

5

You should use this way:

var chk01 = $('#chk01').is(':checked');
var chk02 = $('#chk02').is(':checked');
var chk03 = $('#chk03').is(':checked');

Try it out:

function teste() {
    var chklista = $('input[name="chklista"]:checked').toArray().map(function(check) { 
        return $(check).val(); 
    });   
    var chk01 = $('#chk01').is(':checked');
    var chk02 = $('#chk02').is(':checked');
    var chk03 = $('#chk03').is(':checked');
    $('#div01').html("por nome: <br />chklista: " + chklista + "<br /><br />por id: <br />chk01: " + chk01 + "<br />chk02: " + chk02 + "<br />chk03: " + chk03 + "<br />");
}

$('#btn01').bind('click', teste);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputname="chklista" id="chk01" value="01" type="checkbox" />01<br />
<input name="chklista" id="chk02" value="02" type="checkbox" />02<br />
<input name="chklista" id="chk03" value="03" type="checkbox" />03<br />    
<br />
<input id="btn01" type="button" value="CLIQUE AQUI PARA TESTAR" />
<br />
<br />
<div id="div01">
</div>

The excerpt:

$('input[name="chklista"]:checked').toArray().map(function(check) { 
    return $(check).val(); 
});

Simply search for all inputs with the name "chklista" that are checked, transform the jquery object that holds a reference to all of them in a conventional array, then we get that array and map each element of the DOM to its value, which you defined in HTML

    
18.12.2014 / 15:22