简体   繁体   中英

Get checkbox value even if not checked?

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?

  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" /> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM