Skip to content

How can I use javascript to add a value to a form before submitting it?

I’m using flask to build a website, and I want to get the local date of the client when they purchase my product and add it to the form when it’s submitted using javascript.

<form id="form" onsubmit="return addTime()" method="post">
<script type="text/javascript">
    // the datetime javascript. Triggers when the form is submitted. 
    function addTime() {
        /*var form=document.getElementById('form');

        var input = document.createElement('input');
        input.setAttribute('local date', new Date());


        var oldhtml = document.getElementById("myform").html();
        var newhtml = `<input type="text" name="local date" value=${new Date()}>`;

I trid two methods. The first one takes the form and adds an attribute to it. I’m not sure if I should use form.submit() after that or not, but neither worked. The second method takes the html of the form and adds the input to it. That also didn’t work.

What am I doing wrong?

Edit: the methods I used are based on this this and this



Appending an input element is correct. But you need to set its value, not local date. That should be the name of the input, not an attribute.

var input = document.createElement('input'); = 'local date';
input.value = new Date().toString();

You don’t need to call form.submit() in your function. That will be done automatically unless the function returns false.