Using jQuery to get the value of the multiple check box and output as a string separated by commas.

advertisements

I have many checkboxs as below,

<li><input type="checkbox" name="areaofinterest" value="home_coo" id="home_coo" class="Checkbox" > Cooking</li>
    <li><input type="checkbox" name="areaofinterest" value="home_cra" id="home_cra" class="Checkbox"> Crafts</li>
    <li><input type="checkbox" name="areaofinterest" value="home_dec" id="home_dec" class="Checkbox"> Decorating</li>
    <li><input type="checkbox" name="areaofinterest" value="home_ent" id="home_ent" class="Checkbox"> Entertaining</li>
    <li><input type="checkbox" name="areaofinterest" value="home_gar" id="home_gar" class="Checkbox"> Gardening</li>
    <li><input type="checkbox" name="areaofinterest" value="home_hom" id="home_hom" class="Checkbox"> Home Improvement</li>
    <li><input type="checkbox" name="areaofinterest" value="home_mar" id="home_mar" class="Checkbox"> Marriage</li>
    <li><input type="checkbox" name="areaofinterest" value="home_par" id="home_par" class="Checkbox"> Parenting</li>
    <li><input type="checkbox" name="areaofinterest" value="home_pet" id="home_pet" class="Checkbox" > Pets</li>
    <li><input type="checkbox" name="areaofinterest" value="home_ret" id="home_ret" class="Checkbox"> Retirement</li>

How can I use jQuery to get the checked values and output as areaofinterest="home_coo,home_mar,home_pet" ?

Thanks a lot.


Use the .map() function:

$('.Checkbox:checked').map(function() {return this.value;}).get().join(',')

Breaking that down:

$('.Checkbox:checked') selects the checked checkboxes.

.map(function() {return this.value;}) creates a jQuery object that holds an array containing the values of the checked checkboxes.

.get() returns the actual array.

.join(','); joins all of the elements of the array into a string, separated by a comma.

Working DEMO