In this article I’m going
to explain how to get multiple checkbox values output as comma separated string
using jQuery.
I got one requirement that I have to get multiple checkbox
values output as comma separated string by using jQuery. Whenever I’m going to
click checkboxes, the checkbox values should be added as comma separated string to textarea
control.
Add
JQuery library:
Please add this JQuery library on <head> section:
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.7.1.js"></script>
Add
Script:
<script type="text/javascript">
function
updateTextArea() {
var
allVals = [];
$('#mydiv
:checked').each(function () {
allVals.push($(this).val());
});
$('#txtValue').val(allVals)
}
$(function
() {
$('#mydiv
input').click(updateTextArea);
updateTextArea();
});
</script>
Add
HTML Markup:
<div id="mydiv">
<input type="checkbox" name="swimmingpool" id="swimmingpool" value="1" />
Swimming Pool<br />
<input type="checkbox" name="fitnesscenter" id="fitnesscenter" value="2" />
fitness center<br />
<input type="checkbox" name="restaurant" id="restaurant" value="3" />
restaurant<br />
<input type="checkbox" name="childrenactivities" id="childrenactivities"
value="4"
/>
children’s activities<br />
<input type="checkbox" name="complimentarybreakfast " id="complimentarybreakfast"
value="5" />
complimentary breakfast<br />
<input type="checkbox" name="meetingfacilities" id="meetingfacilities"
value="6"
/>
meeting facilities<br />
<input type="checkbox" name="petsallowed " id="petsallowed " value="7" />
pets allowed<br />
<textarea id="txtValue"></textarea>
</div>