up vote 1 down vote favorite
share [fb]

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.

link|improve this question

feedback

1 Answer

up vote 2 down vote accepted

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.

link|improve this answer
+1 Very tidy solution. Only thing I'd add is to change the selector to $("input[name='Region']:checked"). – GenericTypeTea Aug 20 '10 at 9:13
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 Aug 20 '10 at 9:38
Emile, I've updated my answer to reflect this. – Matt Aug 20 '10 at 9:55
Matt very elegant!! Thank you!! – Emile Aug 20 '10 at 10:03
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.