jQuery

jQuery Comma Separated List Examples

Sometime or the other, you may have worked with arrays in jQuery. And many times, you may have come across a situation where you need to show array values in a comma separated list, instead of just showing the individual array values. So do you know how to make  Comma Separated List ? In this article, I am going to share a solution to very easily make comma separated list of array values using jQuery.

Examples to Make Comma Separated List out of Array Value using jQuery

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 values of the checked checkboxes.

Example: Here is the full source code to make comma separated list out of array values 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>
<input type="checkbox" name="fruits[]" class="fruits" value="apple" id="fruits_0">
Apple</label>
<br>
<label>
<input type="checkbox" name="fruits[]" class="fruits" value="mango" id="fruits_1">
Mango</label>
<br>
<label>
<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(comma_separated_list);

return false;

});

});

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

When you run the above code, click on the button and that will give the comma separated list of the checked checkboxes values.

Simple, isn’t it?

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

Share your thoughts, comment below now!

*

*