【问题标题】:Combobox Value Disappears After Select选择后组合框值消失
【发布时间】:2014-01-07 19:33:58
【问题描述】:

我的 JSP 页面上有两个组合框。它们的值来自 JSON 页面。当您从第一个组合框中选择一个值时,第二个组合框值将根据第一个组合框的 id 列出。第一个组合框是国家名称,第二个是城市名称。

<select onchange="ListCities()" id="ListCountries">
<%       String CountryId,CountryName;
         for(int k=0;k<= jsonarray.length()-1;k++ )
           {
           CountryId = jsonarray.getJSONObject(k).get("id").toString();
           CountryName = jsonarray.getJSONObject(k).get("name").toString();
           out.print("<option value=" + CountryId +">" +CountryName+ "</option>");
           }      
%>
</select> 

<select id="ListCities">
<%       String CityId,CityName; 
         for(int k=0;k<= jsonIlArray.length()-1;k++ )
           {
           CityId= jsonCityArray.getJSONObject(k).get("id").toString();
           CityName= jsonCityArray.getJSONObject(k).get("name").toString();
           out.print("<option value=" + CityId+">" +CityName+ "</option>");
           }  

%>

function ListCities() {
    var CountryIdFromCB = document.getElementById("CountryList").value;
    document.location.href = ('?CountryId='+ CountryIdFromCB); 
   }

组合框的值工作正常。当您从第一个组合框中选择任何项目时(第二个框根据第一个组合框的 id 列出),JSP 页面将第一个组合框的 id 作为参数传递给第二个组合框。但是,刷新页面时,选定的组合框项会消失。即使用户从第二个组合框中选择任何项目,我也想保留第一个组合框的值。

我不想使用 JQuery,我正在寻找纯 Javascript 的解决方案。

谢谢,马克

【问题讨论】:

  • 如果您的页面在您更改国家/地区值时加载,最好将所选国家/地区值保留在 java 变量中,并使用 document.getElementById("ListCountries").selectedIndex = Your_selected_country; 等 JavaScript 选择您的国家/地区
  • 通过 selectedIndex 方法,我们可以得到该元素在下拉列表中的行号。但是,堆栈号与国家/地区的唯一 ID 不同。他们不一样。例如,法国列在列表的第 5 行,但实际上 France.id 是 3。

标签: java javascript jsp parameters combobox


【解决方案1】:

该问题与“selectedIndex”无关。它与选择选项的“选定”属性有关。

您丢失了第一个选择的下拉菜单,因为您没有处理“已选择”属性。这是第一个下拉菜单的代码:

<select onchange="ListCities()" id="ListCountries">
<%
    String CountryId,CountryName;
    for(int k=0;k<= jsonarray.length()-1;k++ )
    {
        CountryId = jsonarray.getJSONObject(k).get("id").toString();
        CountryName = jsonarray.getJSONObject(k).get("name").toString();

        if (CountryId.equals(request.getParameter("CountryId")))
        {
            out.print("<option value=" + CountryId +" selected>" +CountryName+ "</option>");
        } else 
        {
            out.print("<option value=" + CountryId +">" +CountryName+ "</option>");
        }           
     }      
%>
</select>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2014-10-09
    • 1970-01-01
    相关资源
    最近更新 更多