开发者

Rails: Using input from dropdown menu without posting

I'm pretty new to Rails and web dev in general. I need to display two dropdown menus, states and schools, such that schools is only displayed after the user has chosen the state, and schools should only display the schools in the chosen state. What I don't know is how I can use the states choice to decide dynamically what schools to display, without the user having to clic开发者_如何学Pythonk Submit. I understand that I may need to use JavaScript, but not knowing JS well, I'm not really sure how to do that. Hope I'm making sense. Thanks!


Here is a simple example of dynamically populating a select based on data structures already in your JavaScript. If you need to perform a server request after the user selects a state and return the list of schools, you'll need different code (and helpfully a library like jQuery).


I think you want to do this with AJAX. I'm not going to customize this for Rails 1 but you should be able to follow the idea. Your first dropdown has a list of states, and each state has a list of schools.

// some js file that's loaded from your layout
// When your states dropdown is changed it fires an ajax call
var success = function(response) {
  for (var school in response.schools) {
    $('#schools_dropdown').html('');
    var option = $(document.createElement('option')).html(school.name).val(school.id);
    option.appendTo($('#schools_dropdown'));
  }
});

$('#states_dropdown').change(function() {
  $.get('/state/' + $(this).val() + '/schools', success);
});

# your schools controller
def index
  @schools = State.find(params[:id]).schools
  respond_to do |format|
    format.js { render :json => @schools }
  end
end

So maybe you don't have jQuery and maybe rendering json is different in Rails 1... but the idea is the same. You have some javascript attached to your states dropdown so that when it changes, you pull off the id of that state and make an AJAX call to your controller. The last parameter to that AJAX call is a success function that loops through all the schools sent back by the controller, clears the schools dropdown, and adds options into the dropdown one by one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜