如何将 javascript 变量分配给隐藏的输入

How to assign a javascript variable to a hidden input?

本文关键字:隐藏 输入 分配 变量 javascript      更新时间:2023-09-26

我想将javascript变量存储到隐藏的输入字段中,因为我想从servlet中获取它。这是我当前的代码:

.HTML:

<form action="myServlet">

<input type="hidden" id="id" value="" name="total">
     <input type="submit" value="Go!"/>
</form>

Javascript:

var a = 2;
document.getElementById('id').value=a;

myServlet (java servlet):

int count = Integer.parseInt(request.getParameter("total"));
        ServletContext context= getServletContext();
        request.setAttribute("count", count);
            RequestDispatcher rd= context.getRequestDispatcher("/newjsp1.jsp");
            rd.forward(request, response);

每当我单击提交按钮时,它都会给出错误NumberFormatException因为 JavaScript 变量没有分配给我尝试使用 servlet 获取的隐藏输入字段。我希望你们能帮助我解决我的困境。谢谢!

您必须在

呈现输入隐藏元素后添加 javascript,即代码排列的顺序很重要,因为您已经添加了在浏览器中渲染时要执行的 javascript。确保没有其他元素具有相同的 id 值"id"。

我更喜欢使用函数在表单提交时执行,如下所示。

    <form action="myServlet" onSubmit="setVal();">
<input type="hidden" id="id" value="" name="total">
     <input type="submit" value="Go!"/>
</form>
<script>        
function setVal(){
   var a = 2;
    document.getElementById('id').value=a;
}
</script>