读取选择框的选定值并将其传递给jsp

问题描述 投票:0回答:1

我是JSP,HTML等新手,并且有一个问题:

我有一个JSP,我正在尝试从HTML选择框中读取选定的值,例如使用JavaScript:

<form name="ListForm" action=""> 
<select name="country" size="6">
<%
    String[] testArray = {"Germany", "Russia", "China", "Iran", "USA", "Israel"};
    for (int i = 0; i < testArray.length; i++) {
%>
        <option value=<%=testArray[i]%>>
        <%= testArray[i] %> 
        </option>
<%
    }
%>
</select> 
</form>

这是JavaScript:

<script type="text/javascript">
    function getSelectedValue() {
        var e = document.getElementById("country");
        return e.options[e.selectedIndex].text;
    }
</script>

现在我想将此String传递给另一个JSP:

<% 
    String testVar = request.getParameter("country");
    session.setAttribute("varName", testVar); 
%>

但这不起作用。你知道为什么吗?

javascript jsp drop-down-menu selectedvalue
1个回答
0
投票

一个可能的问题可能是您的选择菜单名称为country但不是id country。因此,您不会使用document.getElementById("country");选择菜单

您可以通过在<select>标记中添加ID来解决此问题:

<select id="country" name="country" size="6">

但是,您不需要javascript将所选值发送到服务器。

您应该在表单中添加一个提交按钮:

<input type="submit" />

并且不要忘记在action标记中配置<form>

<form name="ListForm" action="[server url]"> 
© www.soinside.com 2019 - 2024. All rights reserved.