0

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?

0

2 Answers 2

1

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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

I have for example this checkbox <input type="checkbox" name="etapes" value="Ouverte" checked="checked"> when I tried your solution I get a blank
1

You can do it using map() method like following.

var str = $('[name="etapes"]:checked').map(function() {
        return $(this).val();
    }).get().join();

console.log(str)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="etapes" value="Ouverte1" checked="checked">
<input type="checkbox" name="etapes" value="Ouverte2">
<input type="checkbox" name="etapes" value="Ouverte3" checked="checked">
<input type="checkbox" name="etapes" value="Ouverte4" checked="checked">

2 Comments

I have a list of checkbox like this <input type="checkbox" name="etapes" value="Ouverte" checked="checked">. Yout proposition give me a blank string
It should work. See updated code snippet. @LamloumiAfif

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.