How to get the value of a list of ckeckboxes with jquery?

Asked

Viewed 8,726 times

2

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 way out was this:

inserir a descrição da imagem aqui

when I wanted something like this:

inserir a descrição da imagem aqui

1 answer

6


You should wear it like this:

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

Try:

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>
<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="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 all the inputs with the name "chklista" that are checked, transform the jquery object that stores a reference for all of them into a conventional array, then we take this array and map each DOM element to its value, which you defined in HTML

Browser other questions tagged

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