views:

59

answers:

1

Hi,

I have a list of US regions set up as checkboxes. When a user submits the form, I need an array of associated states. This array is used for comparing to another array in my SQL tables.

Using jQuery or javascript, what's the best way to go about this?

I've got the general idea I believe:

        //populate region to state arrays here

        $("input[name='region']").each(function () {
            if ($(this).is(':checked')) {

            // ADD TO SUPER ARRAY OF ALL REGIONS
            // (this is where I need help)

            }
        });

Thanks in advance!!

PS. I tried using the input values var regionValue = $(this).attr('value') to identify each array, but I'm having issues with dynamically named arrays since all my functions are in static classes.

+2  A: 

Edited to reflect the new information and incorporating GenericTypeTea's comment:

Assuming the ID of each checkbox is set to the region name, how about:

var regionStates = {};
regionStates['northeast'] = ['AB', 'CD', 'EF'];
regionStates['mountains'] = ['GH', 'IJ', 'KL'];
// etc...

var selectedStates = [];
$("input[name='region']:checked").each(function () {
    var region = regionStates[this.id];
    for (var i = 0; i < region.length; ++i) {
        selectedStates[selectedStates.length] = region[i];
    }
});

Using this, selectedStates will contain all the states of all regions that are selected.

Apologies for not knowing any real US state abbreviations.

Matt
+1 Very tidy solution. Only thing I'd add is to change the selector to `$("input[name='Region']:checked")`.
GenericTypeTea
Sorry--may have not made myself entirely clear. Each region checkbox is associated with an array of states. As I understand this solution would add an individual state to the next open array slot. So for instance: northeast, mountain, pacific are checked. I make arrays populating each region with respective states. How does superArray become the combination of all those regional arrays? Thanks! Sorry for being unclear.
Emile
Emile, I've updated my answer to reflect this.
Matt
Matt very elegant!! Thank you!!
Emile