Skip to content

How to select checkboxes from comma separated list with jQuery

by Wayne Denier on September 15th, 2010

If you have checkboxes that are grouped by having the same name, the value sent via POST will contain all the selected item values as a comma separated list. I inherited some code that was doing this and wanted a quick way of taking this same comma separated value and reselecting the checkboxes from it. The following Javascript snippet I developed using jQuery does just that.

// Takes comma-delimited list of preselected values and selects html checkboxes
$(document).ready(function(){
var array = "<%=originalValue%>".split(',');
for (var i in array)
$("[name=myCheckboxName][value=" + $.trim(array[i]) + "]").attr('checked', true);
});
No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS