HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Show list of states depending on user selection

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
showselectionuserstatesdependinglist

Problem

I have some data that needs to bind to my view depending on the user selection.

Example: changing the list of states in a dropdown depending on the selected country.

My understanding is, there are two ways to do this:

  • Have a global JS variable, say,


var model, which has a property, "states". This contains all the relevant data of states.

So, I bind the data from the "states" property of the model variable depending on the selection of country.

Code:

In my view:


   USA
   CHINA
   INDIA

    var model = @Html.Raw(Json.Encode(Model)); //Model is my C# object that I am converting into a JS object


In my JS:

$(document).ready(function () {
    stateSelection(model.StateList)
})

function stateSelection(stateList) {
        var jStates = jQuery('select[name="state"]');
        var selectedCountry = jQuery('select[name="country"] option:selected').val();
        var provinceExists = false;
        jStates
                .children()
                .remove()
                .end()
        if (stateList.length > 0) {
            jQuery.each(stateList, function (key, val) {
                if (selectedCountry === val.ID) {
                    jStates
                        .append('' + val.Text + '');
                }
            });
        }
    }


-
Make an ajax call whenever the country dropdown selection is made, then pass the country name/id as parameter and get a response object that contains the list of states that I want to display, and bind them to my view.
In my JS:

$.ajax({
    type: "POST",
    url: Home/GetStates,
    data: $('select[name="country"] option:selected').val(),
    error: function (xhr, status, error) {
    },
    success: successFunction
});

function successFunction(data) {
    stateSelection(data) //data contains the list of states
}


My question basically is, is it bad practice to have a rather large JS object (list of states) as a global variable - or does it make sense to get only the data I n

Solution

Regarding your question about downloading all options at once versus fetching the state options dynamically using ajax, the answer depends on just how big the state list is, but probably the right answer is to download them all at once.

File Size Considerations

Consider that jquery, which you are already including, is about 30KB minified and compressed. My guess would be that your state list is small compared with that, so you shouldn't worry about downloading the whole thing at once. If that assumption is wrong, then ajax might be a reasonable choice.

UX Considerations

Think about the user experience when the entire state list is downloaded. Making a new a country selection will instantly repopulate the states -- a seamless experience. If you have to use ajax, there will be a pause between the user's country selection and when the states become available. This is awkward, and ideally, if you do this, you'd display an ajax spinner (or some other indication that you are waiting for a network response). This will make your code more complex, and can be difficult to get exactly right. For example, you'd need to make sure you handle errors gracefully, and show appropriate messages to the user. If you don't use ajax, you simply avoid all these issues.

So my advice would be to avoid ajax unless you really need it -- eg, your state lists are huge and you know you'll be supporting users with slow connections.

Context

StackExchange Code Review Q#105997, answer score: 2

Revisions (0)

No revisions yet.