javascript以动态填充下拉列表框 [英] javascript to dynamically populate a dropdown list box

查看:78
本文介绍了javascript以动态填充下拉列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ruby on rails应用程序.我有2个下拉框.我必须根据第一个下拉框的选择填充第二个下拉框.

I have a ruby on rails application.I have 2 drop down boxes.I have to populate the second drop down box based on the selection from the first one.

html代码是

-Releases = Release.all
  %table.grid.full
    %tr      
      %td.grid.full_panels{:style => "width: 40%"}
        Release:
      %td.grid.full_panels{:style => "width: 40%"}
        = select_tag "releases",options_from_collection_for_select(releases,"id","name",params[:releases]),:include_blank=>true
      %td.grid.full_panels{:style => "width: 40%"}
        Cycle:
      %td.grid.full_panels{:style => "width: 40%"}

现在我需要从发行版中填充下来的周期.

Now i need the cycles drop down to be populated from releases.

请帮助我解决这个问题.

Please help me with the jquery for this.

推荐答案

基本上,您应该添加一个事件处理程序,该事件处理程序将在更改第一个下拉菜单时触发,该事件处理程序将根据第一个下拉菜单的选定选项填充第二个:

Basically you should add an event handler that will be triggered when the first drop-down is being changed that populates the second one based on the first one's selected option :

$('select#first').change(function(e){
    var newOptions = getNewOptions($(this).val());
    $('select#second').html('');   // clear the existing options
    $.each(newOptions,function(i,o){
        $('<option>' + o + '</option>').appendTo('select#second');
    });            
});

function getNewOptions(val){
    if (val == 1)
        return ['a','b','c'];
    if(val == 2)
        return [1,2,3,4];
    return ['a1','a2','a3'];
}

当然,您的html标记类似于:

And of course, your html markup is something like :

<select id="first">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

<select id="second">
</select>

这是一个有效的演示:

http://jsfiddle.net/gion_13/Udf5N/

Here's a working demo :

http://jsfiddle.net/gion_13/Udf5N/

如果要在服务器上查询新选项列表,请在更改事件处理程序中向脚本发出ajax请求,以评估第一个选择框的当前值并返回该选项列表.第二个.在此ajax请求回调中,您将根据响应更新实际的html:

If you want to query the server for the new option list, in the change event handler, you should do an ajax request to the script that evaluates the current value of the first select-box and returns a list of options for the second one. In this ajax request callback you update the actual html based on the response :

$('select#first').change(function(e){
    $.getJson('script_name',{value : $(this).val()},function(result){
        $('select#second').html('');   // clear the existing options
        $.each(result,function(i,o){
            $("<option>" + o + "</option>").appendTo("select#second");
        }); 
    });            
});

这篇关于javascript以动态填充下拉列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆