user3418987
user3418987

Reputation: 137

How to assign a javascript variable to a hidden input?

I wanted to store a javascript variable to a hidden input field because I wanted to get it from a servlet. This is my current code:

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);

whenever I click the submit button, it gives the error NumberFormatException because the javascript variable is not assigned to the hidden input field that i'm trying to get using a servlet. I hope you guys can help me with my dilemma. Thanks!

Upvotes: 0

Views: 3467

Answers (1)

Kiran Krishnan
Kiran Krishnan

Reputation: 81

You have to add the javascript after the Input Hidden element is rendered, ie order of the code arrangement is important since you have added the javascript to execute when it is rendered in browser . Make sure no other element has the same id value "id".

I prefer to use a function to execute on form submit as follows.

    <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> 

Upvotes: 2

Related Questions