Reputation: 7583
I have a set of checkboxes which all have the same name called 'Department'. Whenever a user checks one or more of these Department
checkboxes I want the values to be seralized and sent via AJAX so that it can retrieve more data based on the selected values.
So far I have done this:
$('#user-Departments input[name="Department"]').change(function () {
var selected = $('#user-Departments input[name="Department"]').serialize();
console.log(selected);
});
So if any of the Department
checkboxes change in the div with id of user-Departments
, then I'm asking JQuery to seralize the values. The value is contained in the ID attribute of each checkbox. But my console is showing this:
Department=4&Department=9
How do I get just the values 4 and 9 into a comma-delimited string e.g. "4,9" so that I can pass it as a list to my web server (Coldfusion)?
ADDED JSFIDDLE: http://jsfiddle.net/mjcJ4/
Upvotes: 0
Views: 578
Reputation: 11062
$('#user-Departments input[name="Department"]').change(function () {
var selected = [];
$('#user-Departments input:checked[name="Department"]').each(function(index) {
selected.push($(this).val());
});
console.log(selected.toString());
});
Upvotes: 2
Reputation: 3065
Using .map()
will be more efficient i guess
$('#user-Departments input[name="Department"]').change(function () {
var selected = $('#user-Departments input[name="Department"]:checked').map(function() {
return this.value;
}).get().join(',');
console.log(selected);
});
Upvotes: 1
Reputation: 2605
$(document).ready(function() {
$("input[name='department']").change(function() {
var departmentIds = [];
var selectedDepartments = $("input[name='department']:checked").each(function(){
departmentIds.push($(this).val());
});
//post the values to the url
$.post("/your/url/", JSON.stringify(departmentIds));
});
});
I've added the values to a collection and then converted the values to json for a post. Notice how i'm only getting the values that are "Checked" (when one of the checkboxes are ticked or unticked).
Upvotes: 2