1

I'm trying to record the date and time of when a user has submitted a form.

I'm required to capture the date and time in a hidden field.

I've created a function which displays the date and time but I'm unable to get this into the hidden input value.

This is the current way I've been trying.

function dateTime() {
  new Date($.now());
}

$("#DateTime").attr("value", dateTime());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="DateTime" name="DateTime" type="" value="">

Any suggestions or ideas on where I might be going wrong would be great.

Thanks in advance!

ikiK
  • 6,328
  • 4
  • 20
  • 40
Danny91
  • 163
  • 1
  • 11
  • 1
    Does this answer your question? [How to add a new hidden input fields to the form on submit](https://stackoverflow.com/questions/9251301/how-to-add-a-new-hidden-input-fields-to-the-form-on-submit) ... https://stackoverflow.com/questions/3350247/how-to-prevent-form-from-being-submitted – ikiK Jul 30 '21 at 11:09
  • Typo. Your `dateTime` function doesn't return anything, you forgot the `return` keyword. – David Jul 30 '21 at 11:10
  • 1
    also "I've created a function which displays the date and time", as seen in the snippet I made code you showed shows nothing. Please create [mre] – ikiK Jul 30 '21 at 11:16

2 Answers2

5

Easy to use moment js for change formate accordingly

<body>

<input id="DateTime" name="DateTime" type="text" value="">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

<script type="text/javascript">
  $(document).ready(function(){
    var today = moment().format('YYYY-MM-DD HH:mm:ss');
    $('#DateTime').val(today);
   // alert($('#DateTime').val());
  });
</script>

</body>
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

<script type="text/javascript">
  $(document).ready(function(){
    var today = moment().format('YYYY-MM-DD HH:mm:ss');
    $('#DateTime').val(today);
   // alert($('#DateTime').val());
  });
</script>
Rajeev Singh
  • 1,724
  • 1
  • 6
  • 23
0

You're not returning anything from function so how you gonna get datetime, try below

function dateTime() {
  return new Date($.now());
}

$("#DateTime").attr("value", dateTime());

here is link to fiddle - https://jsfiddle.net/zp3qhm9x/1/

Ankit Bisht
  • 78
  • 1
  • 10
  • is it possible to change the format of this date and time to something like this 2021-07-30T13:00:07 – Danny91 Jul 30 '21 at 12:06