javascript - Get a list of all checked checkboxes -
i figure out checkboxes checked , tried code:
$('.feature input[type="checkbox"').serialize();
this how 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 output 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 know of them has been checked? , signs %5b%5d mean?
about: %5b%5d
answer: raw http encoded values of "[]" (result of serialize function).
when server parses converts [] , sends application threat array.
about why getting dummy: "feature%5b%5d=on&feature%5b%5d=on..." string
answer: you've forgot give every checkbox value parameter, like: "feature%5b%5d=custom_css&feature%5b%5d=custom_js..."
i've wrote solution.
take working example , handle "feature" param of request on server-side app string , shrink "," (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
Post a Comment