Reza Reza - 4 months ago 7
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">
<h2>Features</h2>
<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>
</div>


And this is the output that I get:


array(1) { ["var_sent_via_ajax"]=> string(67)
"feature%5B%5D=on&feature%5B%5D=on&feature%5B%5D=on&feature%5B%5D=on"
}


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

Answer

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() {
      features.push($(this).val());
    });
    $('#selectedFeatures').html(features.join(','));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="feature">
  <h2>Features</h2>
  <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>
</div>

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

Comments