Reza Reza - 1 year ago 80
Javascript Question

Get a list of all checked checkboxes

I would like to figure out which checkboxes are checked and so I tried this code:

$('.feature input[type="checkbox"').serialize();

This is how my HTML looks like:

<div class="feature">
<label><input class="custom_css" checked="" type="checkbox" name="feature[]"> Custom CSS (style.css)</label>
<label><input class="custom_js" checked="" type="checkbox" name="feature[]"> Custom Javascript (script.js)</label>
<label><input class="modernizr" type="checkbox" name="feature[]"> Modernizr</label>
<label><input class="google_maps" type="checkbox" name="feature[]"> Google Maps</label>
<label><input class="custom_api" type="checkbox" name="feature[]"> Custom API</label>
<label><input class="font_awesome" type="checkbox" name="feature[]"> Font Awesome</label>

And this is the output that I get:

array(1) { ["var_sent_via_ajax"]=> string(67)

Now how can I know which of them has been checked? And what do the signs %5B%5D mean?

Answer Source

About: %5B%5D
Answer: they are simply raw http encoded values of "[]" (result of serialize function).
When server parses it converts to [] and sends to application that will threat it as an array.

About why You are getting dummy: "feature%5B%5D=on&feature%5B%5D=on..." string
Answer: You've forgot to give every checkbox a value parameter, then they will be like: "feature%5B%5D=custom_css&feature%5B%5D=custom_js..."

I've wrote solution.
Take this working example and handle "feature" param of request on server-side app like a string and shrink it by "," (php: $features = explode(',', $_POST['features']);

$(function() {
  $('#getFeatures').click(function() {
    var features = [];
    $('.feature input[type="checkbox"]:checked').each(function() {
<script src=""></script>

<div class="feature">
  <label><input class="custom_css" checked="" type="checkbox" name="feature[]" value="custom_css"> Custom CSS (style.css)</label>
  <label><input class="custom_js" checked="" type="checkbox" name="feature[]" value="custom_js"> Custom Javascript (script.js)</label>
  <label><input class="modernizr" type="checkbox" name="feature[]" value="modernizr"> Modernizr</label>
  <label><input class="google_maps" type="checkbox" name="feature[]" value="google_maps"> Google Maps</label>
  <label><input class="custom_api" type="checkbox" name="feature[]" value="custom_api"> Custom API</label>
  <label><input class="font_awesome" type="checkbox" name="feature[]" value="font_awesome"> Font Awesome</label>

<button id="getFeatures">GET FEATURES</button>
<div id="selectedFeatures"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download