Passing multiple checkbox values in AJAX call

I use a ternary operator to check which checkboxes in a form have been selected. If a value has been selected, I affix the name-value pair to a query string which is then passed in an AJAX call. If not, I attach a name with an empty string value.

It works fine, I'm just wondering if there's a more compact/elegant way to do this as it seems somewhat verbose. I'm wondering if it's possible to use a for loop. The reason I'm not sure if this would work is it would involve dynamically assigning variable names within the loop based on the index.

    var fields = $('input[name="apn"]').serializeArray();
    var apn1 = fields[0] ? fields[0]["value"] : '' 
    query += '&apn1=' + apn1;
    var apn2 = fields[1] ? fields[1]["value"] : '' 
    query += '&apn2=' + apn2;
    var apn3 = fields[2] ? fields[2]["value"] : '' 
    query += '&apn3=' + apn3;
    var apn4 = fields[3] ? fields[3]["value"] : '' 
    query += '&apn4=' + apn4;
    var apn5 = fields[4] ? fields[4]["value"] : '' 
    query += '&apn5=' + apn5;
    ...

Answers


Map the values and indices to an array of objects, and just pass that directly to $.ajax, jQuery will use $.param on it for you :

var fields = $.map($('input[name="apn"]'), function(el, i) {
    var o = {};
    o['apn' + i] = el.value;
    return o;
});

If its just checkboxes:

$('input[name="apn"]').each(function (i, el) {
    if($(el).is(':checked')) {
        query += '&apn'+i+'=' + el.value;
    }
});

You can simply serialize the form:

var query = $("#FormId").serialize();

Need Your Help

Why Doesn't IOS Core BLuetooth Respect Communication Rate

ios xcode bluetooth core-bluetooth

I am writing a Core Bluetooth App for IOS. It is connecting to a TI device With custom firmware. The firmware developer developed it to publish data 12 times a second. I am using the Notify Prop...

Most memory efficient way to save a photo to disk on iPhone?

ios iphone objective-c uiimage avfoundation

From profiling with Instruments I have learned that the way I am saving images to disk is resulting in memory spikes to ~60MB. This results in the App emitting low memory warnings, which (inconsist...