0

Is there a way to get the values of all checkboxes, even if they are not checked?

HTML:

<input type="checkbox" name="color[]" value="1"/>
<input type="checkbox" name="color[]" value="2"/>
...

JS:

$("input[name='color[]']").serialize();

Something like the above, but I want the values even if they are not checked. Perhaps I need to put them into an array first before serialising?

3
  • 1
    Just out of curiosity, why do you want all values? Commented Jun 16, 2015 at 14:31
  • If the all checkbox is clicked, I'll want all values, even if they are not ticked. Commented Jun 16, 2015 at 14:37
  • @panthro, see my updated answer which avoids changing the original state of the checkbox Commented Jun 16, 2015 at 14:37

2 Answers 2

2

The simple solution seems to be missing, so:

var serializedValues = $('input[name="color[]"]').map(function(i, e) {
  return encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value);
}).get().join("&");
snippet.log(serializedValues);
<input type="checkbox" name="color[]" value="1" />
<input type="checkbox" name="color[]" value="2" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

That's assuming you really want the same output that seralize would give you.

Sign up to request clarification or add additional context in comments.

2 Comments

Im sorry, simple? You are doing it by hand! :) Now, better performance, yes, absolutley
@AmmarCSE: What, that's not simple? ;-) (Yeah, that was kinda overselling it...)
2
  1. Clone them to avoid altering the original state of the checkboxes
  2. Set the cloned items checked to true
  3. Serialize

document.write($('input[name="color[]"]').clone().prop('checked', true).serialize());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="checkbox" name="color[]" value="1" />
<input type="checkbox" name="color[]" value="2" />

3 Comments

dont ever use document.write.
@NCA, I only use for demo purposes so readers dont have to open the console or get an annoying alert
@NCA: Would be nice if they would ever get around to implementing this snippets feature, wouldn't it? Then people wouldn't have cause to use document.write in answers...

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.