1

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

        form.appendChild(input);
        form.submit();*/

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

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

  • Don't change the HTML of the form. That will clear all the form fields that the user filled in. – Barmar Aug 28 '21 at 00:09
  • Why did you put /* and */ in between the code? JavaScript will skip comments. –  Aug 28 '21 at 00:16

3 Answers3

1

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');
input.name = 'local date';
input.value = new Date().toString();
form.appendChild(input);

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I would include the input text field in the HTML code for the form, such as this:

<input type="hidden" name="local date" id="localdate" />

In the JavasScript code use something along these lines:

function enterdate(field_id) {
    var field = document.getElementById(field_id);
    var newdate = prompt("Enter a new name");
    if (newdate != null) {
        field.disabled = false;
        field.value = newdate;
        return true;
    } else {
        return false;
    }
}

On form form submit button, use onClick="return enterdate('localdate)".

0

Don't add input to a form on submit it,,
prefer to use type="hidden" attribute

<form id="my-form" method="post">
  <input name="local-date" type="hidden" value="">

JS

const myForm = document.getElementById("my-form") 

myForm.onsubmit = e =>
  {
  myForm['local-date'].value = new Date().toLocaleString('en-US') 
  }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40