volume one
volume one

Reputation: 7583

How to seralize values of checkboxes to pass via AJAX?

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

Answers (3)

martincarlin87
martincarlin87

Reputation: 11062

http://jsfiddle.net/mjcJ4/7/

$('#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

Batu.Khan
Batu.Khan

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);
});

UPDATED FIDDLE

Upvotes: 1

Mike
Mike

Reputation: 2605

http://jsfiddle.net/3K6mL/

 $(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

Related Questions