Lamloumi Afif Lamloumi Afif - 2 months ago 9
HTML Question

Get checked values of checkbox list using jquery

I have a couple of checkbox with the name

etapes
. I'd like to get all the checked
etapes
's value and store it in a single string.

So tried this :

$('[name="etapes"]:checked').each(function() {
indexer = indexer + 1;
if (indexer == 1) selectedEtapes = $(this).val();
else selectedEtapes = selectedEtapes + "," + $(this).val();
});


but it didn't work. SO how can I fix this issue?

Answer

Easier solution is to use jQuery.map

var mapped = $('[name="etapes"]:checked').map(function() {
  return this.value;
}).get();
console.log(mapped.join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" name="etapes" value="Ouverte1" checked>
<input type="checkbox" name="etapes" value="Ouverte2">
<input type="checkbox" name="etapes" value="Ouverte3" checked>

Fix for your code:

You never accepted index argument,

var selectedEtapes = '';
$('[name="etapes"]:checked').each(function(index) {
  if (!index) selectedEtapes += $(this).val();
  else selectedEtapes += "," + $(this).val();
});