Tuesday, January 27, 2009

Changing Select Box data via Ajax from Rails

I needed to change the items in a select input control in response to the changing selection of another select input control.

So I registered a change event on the first select input control by:


$('#control_strategy').delegate('change', '#control_strategy', function(){
get_possible_durations();
});


The get_possible_durations function is as follows:


function get_possible_durations() {
data = {};
data['control_strategy_id'] = $('#control_strategy').val();

$.get("/control_events/duration_increment.js?" + jQuery.param(data), null, function(data) {
var options = '';
data = eval(data);
$.each( data, function( n ) {
options += '<option value="' + this[1] + '">' + this[0] + '</option>';
} );
$( "#duration" ).html( options );
});
}



This function simply makes an ajax call passing in a single parameter based on the value in first drop down. It then responds to the completion of the ajax call by building an "option list" and replacing the html of the second select input control.

The Controller Method that I call is simply:


def duration_increment
data = durations_for_strategy(params[:control_strategy_id])
respond_to do |format|
format.js {render :json => data.to_json}
end
end


The duration_for_strategy method just builds a nice nested array of the data that I need to show...the important part is:



values = []
.
.
.
values << [pretty_up(last_time_added), last_time_added]


No comments: