How to know which checkbox are selected?

Asked

Viewed 136 times

1

How do I make a javascript code to know which checkbox are selected and when finding, get the value data-id his?

<input type="checkbox" data-id="1">
<input type="checkbox" data-id="2">
<input type="checkbox" data-id="3">

I need something like this:

s = '';
for (checkbox){
  if (checkbok.checked) { s+= checkbox.data-id.val(); }
}
alert(s);
  • 1

    None of these questions has what you’re looking for?

  • @Andersoncarloswoss I think we can solve yes, I’ll see if I make the adaptation here. Thank you

  • @Italorodrigo js pure or jquery ?

  • @Weessmith can be jquery, I am importing the file . js

4 answers

5

Just use querySelectorAll('input[type=checkbox]:checked') to select all fields marked and use the attribute dataset to access the value of data-id.

const checkboxes = document.querySelectorAll('input[type=checkbox]:checked');

for (let checkbox of checkboxes) {
  console.log(checkbox.dataset.id);
}
<input type="checkbox" data-id="1" checked>
<input type="checkbox" data-id="2">
<input type="checkbox" data-id="3" checked>

  • 1

    I didn’t know about this selector @Andersoncarloswoss, thanks for the info!

2


I added a test button so you can understand that var s must be inside the event so there is no repeat result:

<input type="checkbox" data-id="1">
<input type="checkbox" data-id="2">
<input type="checkbox" data-id="3">
<button id="teste">teste</button>
<script type="text/javascript">
    $("#teste").click(function(){
        var s = '';
        $.each($('input[type="checkbox"]'),function(){
            if($(this).is(":checked")){
                s+=$(this).data("id");
            }
        });
        alert(s);
    });
</script>

Board from @Andersoncarloswoss:

$.each($('input[type="checkbox"]:checked'),function(){
    s+=$(this).data("id");
});
  • 1

    One detail: the same selector I used works on jQuery. If you do $('input[type="checkbox"]:checked') you don’t need the if.

1

var s = "";
$("input[type=checkbox]").each(function () {
    if ($(this).prop("checked")) {
        s += $(this).attr("data-id") + ",";
    }
});
alert(s);

1

Also using .map() you have as a result a string with comma separated values. Example:

// Faz tudo de uma vez: declara a variável, cria a array,
// converte em string e atribui à variável

const s = $("[type='checkbox']:checked").map(function(){
   return this.dataset.id;
}, []).get().join();

console.log(s); // imprime: 1,3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" data-id="1" checked>
<input type="checkbox" data-id="2">
<input type="checkbox" data-id="3" checked>

You can take the data-* in two ways:

Pure Javascript: elemento.dataset.NOME

jQuery: $(seletor).data("NOME");

Where:

<input data-id> ← elemento
            ↑↑
           NOME

Browser other questions tagged

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