简体   繁体   中英

Passing a javascript variable in a JSP form

I want to pass a value calculated on the client-side, back to the server. Here is my code:

    <script>
        var today = new Date();
        function startTime() {
            document.getElementById('time').innerHTML = today.getTime();
            t = setTimeout(function () {
                startTime()
            }, 1);
        }
        startTime();
    </script>

    <form method="POST" action="../frontier/warehouseops/servlet/TimeCalculator">
        <input type="hidden" name="time" value="time"/>  
        <input type="submit" value="Submit" name="buttonSubmit"/>  
    </form>

What I want to happen is that the value of the javascript variable "time" gets passed to the server. But what is happening, is simply the string "time" is being passed to the server. How do I access the value of a javascript variable and pass it back to the server in a form?

instead of:

document.getElementById('time').innerHTML = today.getTime();

try this:

document.getElementsByName("time")[0].value = today.getTime();

Well

<input type="hidden" name="time" value="time"/>  

This line will pass string "time" only as the value attribute of this hiddle form field has "time" as string. What you realy need to do is write a javascript function onSubmit of form and then set the value of this parameter to whatever you want.

<script>
function submit(form)
{
form.time.value = new Date();
document.getElementById("myForm").submit();
}
</script>
  <form id="myForm" method="POST" action="../frontier/warehouseops/servlet/TimeCalculator">
        <input type="hidden" name="time" value="time"/>  
        <input type="submit" value="Submit" name="buttonSubmit" onClick="submit(this.form)"/>  
    </form>

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM