jQuery

jQuery Comma Separated List Of Labels for Checked Checkboxes

If you have read my previous article on how to make  jQuery Comma Separated List of values, then this article would be of interest to you. In this article, I am going to share a solution to very easily make comma separated list of labels for checked checkboxes using jQuery. Read on to find out more.

Examples to Get Comma Separated List of Labels for Checked Checkboxes using jQuery

Using jQuery Comma Separated List Of Labels for Checked Checkboxes can be made very easily. Let’s consider this with an example. Assume that we have set of checkboxes (array). Now we wish to use jQuery to make comma separated list from the labels of the checked checkboxes. For this, it is mandatory to have labels for each of the checkboxes and the labels should point out to the ID of the respective checkbox.

Example: Here is the full source code to get comma separated list of labels using jQuery

<html>
<head>
<title>jQuery Comma Separated List |Make Comma Separated List of Array values</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>

<body>
<p>
	<label for="fruits_0">
		<input type="checkbox" name="fruits[]" class="fruits" value="apple" id="fruits_0">
		Apple</label>
	<br>
	<label for="fruits_1">
		<input type="checkbox" name="fruits[]" class="fruits" value="mango" id="fruits_1">
		Mango</label>
	<br>
	<label for="fruits_2">
		<input type="checkbox" name="fruits[]" class="fruits" value="grapes" id="fruits_2">
		Grapes</label>
	<br>
</p>

<input type="submit" name="btn_alert" id="btn_alert" value="Alert Comma Seprated List" />

<script type="text/javascript">

$(document).ready(function() {

	$('#btn_alert').click(function(){

		var comma_separated_list = $(".fruits:checked").map(function() {
										return $(this).val();
										}).get().join();

		//Alert the VALUE of checked checkbox					
		alert(comma_separated_list);

		var comma_separated_list_label = $(".fruits:checked").map(function() {

								return $.trim( $("label[for='"+$(this).attr("id")+"']").text() );

										}).get().join();

		//Alert the LABEL of checked checkbox					
		alert(comma_separated_list_label);											

		return false;

	});		

});

</script> 
</body>
</html>

Simply run the above code & click on the button. That will give the comma separated list of the checked checkboxes labels.

That’s it!

Do you know of any other ways to make comma separated list of checked checkboxes labels using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*