我通过父下拉列表(第一个下拉列表)中的onchange事件填充子下拉列表(第二个下拉列表)。之后,通过子下拉列表的onchange事件,我将自动填充三个文本框。但是我的问题是第一个下拉列表。第一个下拉列表的comboID为,第二个下拉列表的ID为combo1。
combo
combo1
当我A从第一个下拉列表中选择时,然后在第二个下拉列表中,我1通过附加下面在auto.jsp中编写的javascript 获得了一个值。但是,当我B在第一个下拉菜单中选择选项时,我进入2了第二个下拉菜单,但是旧值1应该从第二个下拉列表中删除,但是仍然保留在那里,为什么?类似地,当我A or B多次从第一个下拉列表中进行选择时,第二个下拉列表中将出现多个值1或2,我要删除它们并显示一次,即如果A将被选中1则将被显示,如果B将被选中2则将被显示, 怎么做到呢?
A
1
B
2
A or B
auto.jsp
<script type="text/javascript"> $(document).ready(function() { $("#combo").change(function() {// by onchange event in first dropdown I populate second dropdown having id combo1 $.getJSON('combo1.jsp', {firstcombobox : this.value}, function(responseData) { $("#combo1").append( $("<option></option>").html(responseData.name).val(responseData.name) ); }); }); // After getting value in second dropdown, by onchange event i am autofilling 3 textboxes. $("#combo1").change(function() { $.getJSON('combo2.jsp', { combo1Val : $(this).val() }, function(data) { $("#firsttextbox").val(data.name); $("#secondtextbox").val(data.roll_no); $("#thirdtextbox").val(data.fine); }); }); }); </script> <body> //First dropdown <select id="combo" name="firstcombobox"> <option value="">select</option> <option value="a">A</option> <option value="b">B</option> </select> // Second dropdown <select id="combo1" name="combo1Val" > <option value="">select</option> </select> </body>
combo1.jsp
<%@page import="net.sf.json.JSONObject"%> <%@page import="net.sf.json.JSONArray"%> <% String firstcombobox=request.getParameter("firstcombobox"); if(firstcombobox.equalsIgnoreCase("a")){// If selected value in first dropdown is A then 1 will be displayed as written below JSONObject arrayObj= new JSONObject(); arrayObj.put("name","1");// I displayed 1 in second dropdown option when A is selected response.setContentType("application/json"); response.getWriter().write(arrayObj.toString()); } else if(firstcombobox.equalsIgnoreCase("b")){ JSONObject arrayObj= new JSONObject(); arrayObj.put("name","2"); response.setContentType("application/json"); response.getWriter().write(arrayObj.toString()); } else{ } %>
在auto.jsp“ #combo”更改匿名功能中,替换为:
$.getJSON('combo1.jsp', {firstcombobox : this.value}, function(responseData) { $("#combo1").append( $("<option></option>").html(responseData.name).val(responseData.name) ); });
与:
$.getJSON('combo1.jsp', {firstcombobox : this.value}, function(responseData) { $("#combo1").empty().append( $("<option></option>").html(responseData.name).val(responseData.name) ); });
要将字符串拆分为数组,请按以下步骤进行操作:如何将字符串拆分为特定字符?
它们的用法如下:
$.getJSON('combo1.jsp', {firstcombobox : this.value}, function(responseData) { var splitValues = responseData.name.split(/,/); $("#combo1").empty().append("<option value="0">Please select...</option>"); for (var idx in splitValues) { $("#combo1").append( $("<option></option>").html(splitValues[idx]).val(splitValues[idx]) ); } });
希望这可以帮助?