java - 在jsp页面中显示选定的文本

标签 java javascript html jsp web

嗨,我是 JSP 的新手,正在尝试将 header 中选定的值显示为动态文本。但每次我选择它时,它都会显示选项值而不是文本。以下是我尝试过的。

Html 下拉列表

<select id="country" name="country_code">
       <option value="1">Puerto Rico</option>
       <option value="63">Philippines</option>
       <option value="others">Others</option>
</select>

JSP标签

    <%
        String countrycd = request.getParameter("country_code");
        String countryTxt = request.getParameter("country_code");
    %>

这是我的脚本

    <script>
        document.getElementById("country").value = '<% out.print(countrycd); %>';
        var e= document.getElementById("country");
        var str = e.options[e.selectedIndex].text;
        alert(str);
    </script>

这是我的 html 代码,我需要显示所选文本而不是值,例如如果用户选择菲律宾,它应该显示为菲律宾而不是代码 63

<h2>By Country: <% out.print(countrycd);</h2>

任何帮助都会非常感激!

谢谢。

编辑:

电流输出

From drop down philipines is selected in header it shows: By Country: 63

预期输出:

From drop down if philipines is selected it should show

By Country: Philipines not 63.

最佳答案

您正在 header 中显示值。您可以通过执行以下操作来实现:

<h2>By Country: <span id="countryName"> </span> </h2>

然后你的脚本应该是:

<script>
  window.onload = function(){        
    document.getElementById("country").value = '<% out.print(countrycd); %>';
    var e= document.getElementById("country");
    var str = e.options[e.selectedIndex].text;

    document.getElementById("countryName").innerHTML = str;  //This line changed
  };
</script>

我们不是使用 JSP 获取国家/地区名称,而是使用 javascript 获取国家/地区名称(将其写在 countryName 范围内)

干杯,来自玻利维亚拉巴斯

关于java - 在jsp页面中显示选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20930468/

相关文章:

javascript - AJAX 请求 - 还清除占位符文本以及 HTML 输入字段值

url 的 java 注释 - 什么是用例?

java sql查询从csv文件导入的数据

javascript - 为什么 sequelize.sync() 不同步表,除非我将模态导入文件?

javascript - 如果表单提交为空,则不会显示错误消息

java - LibGDX 删除 GWT 窗口填充

java.sql.SQLException [Microsoft] [ODBC SQL Server 驱动程序] [SQL Server] 无效的对象名称 'table name'

java - 静态方法作为独立类更慢?

javascript - 预期是赋值或函数调用,但看到的是 JavaScript 表达式

javascript - 有什么方法可以在 jssor slider 中为图像添加框阴影?