views:

272

answers:

1

In the form that we designed, we have a "States" field that allows its users to select multiple states at a time. There is a "City" field which should be populated as per the selection in the "State" field. The values in the "City" field are correctly populated if only one state is selected. However, it is not showing correctly when multiple states are selected.

Please suggest a Ruby solution for the same.

+1  A: 

The problem is the :with expression in your observe_field. document.getElementById('usa_states_').value will only return a single value and not all the selected values.

I'm not sure if there is a way to handle this automatically in Rails but one solution is to write a JavaScript function which will build a string of all the selected values separated by commas. e.g.

function selectedValuesAsString(multiselect) {
    selectedValues = new Array();
    for (i = 0; i < multiselect.length; i++) {
        if (multiselect[i].selected) {
            selectedValues.push(multiselect[i].value);
        }
    }
    return selectedValues.join();
}

and then update the :with to be something like:

:with => "'state='+selectedValuesAsString(document.getElementById('usa_states_')"

and then finally split the values inside your controller action.

mikej
Thanx dude it works. Thanks a million.
Aditya