根据另一个选择框填充选择框

时间:2014-01-19 15:37:49

标签: java javascript jquery ajax

有两个选择框,它们都是从database填充的。第二个选择框应根据从第一个选择框中选择的值进行填充。第一个选择框已经填充但我无法填充第二个选择框

<select id="country_obj" name="custCountry" class="field_size_e">

    <%
                                    Iterator contryIter = countries.iterator();
                                    Lookup lookup = null;
                                    while(contryIter.hasNext()) {
                                        lookup = (Lookup)contryIter.next();
                                        if(bbForm.getCircuit().getCustCountry().equalsIgnoreCase(lookup.getLabel())){
                                            out.print("<option selected=\"selected\" value='"+lookup.getValue()+"'");
                                            out.print(">");
                                            out.print(lookup.getLabel());
                                            out.println("</option>");
                                        }else{
                                        out.print("<option value='"+lookup.getValue()+"'");
                                        out.print(">");
                                        out.print(lookup.getLabel());
                                        out.println("</option>");
                                        }
                                    }
                                %>
    </select>

如何根据第一个选择框

的值填充第二个选择框

1 个答案:

答案 0 :(得分:0)

您可以在javascript中使用函数来填充第二个选择标记的选项。

function populate(val)
{
   //val is a string similar to "<option value='new_option'>new option</option><option...</option>..."
   $('#my_select2').append(val);
}

//below method is triggered whenever you select a value for your first select box
$("#country_obj").change(function(){
   var selected_str = $("#country_obj option:selected").text();
   //now pass this selected_str to a php page where options generation method is          present using $.ajax (refer http://api.jquery.com/jQuery.ajax/)
   //or you can implement the method here (in javascript) to generate options for your new select tag.
   }

})

注意:这仅供参考。您可以将两种方法的实现合二为一,也可以有多种方法。我会留下你的决定。

编辑:你不能在同一个php页面中为你的第二个选择标签生成选项(就像在你的问题中一样),因为,当你的页面被加载并且用户选择第一个选择标签的值时你的PHP代码已经执行了。