CusterN
CusterN

Reputation: 93

Copy Date / DateTime from one Html Input to another Html Input with Javascript

I have 2 a elements. Both open a Bootstrap modal. This a element is used to create a brand new record, and so it sends the current date/time:

<a style="color:#5cb85c" data-CreateDate="@DateTime.Now" data-toggle="modal" data-target="#OnPostModal" href="#OnPostModal" class="fas fa-plus-circle"></a>

The other a element carries some fields from a record that was already created, so it sends that pre-existing create date with it.

<a data-toggle="modal" data-target="#OnPostModal" data-CreateDate="@item.Supplier.CreateDate" href="#CallModal" class="fas fa-edit"> </a>

I use some JavaScript to fill a field on the modal that pops up:

<script type="text/javascript">
    $('a[data-toggle=modal], button[data-toggle=modal]').click(function () {

        var data_CreateDate = '';

        if (typeof $(this).data('CreateDate') !== 'undefined') {
            data_CreateDate = $(this).data('CreateDate');
        }

        $('#CreateDate').val(data_CreateDate);
    })

</script>

Lastly, this is the area in the modal that needs filled:

<div class="form-group">
   <label asp-for="Supplier.CreateDate" class="control-label"></label>
   <input asp-for="Supplier.CreateDate" id="CreateDate" class="form-control" />
   <span asp-validation-for="Supplier.CreateDate" class="text-danger"></span>
</div>

This method works for string values, but doesn't seem to work at all for DateTime or Date values. I have tried:

var data_CreateDate = new Date();

That doesn't work.

Upvotes: 0

Views: 636

Answers (1)

terrymorse
terrymorse

Reputation: 7086

new Date() returns an object. You want a string. Several formats to choose from:

const output = document.getElementById('output');
const d = new Date();
output.innerText = d.toString() + '\n';
output.innerText += d.toISOString() + '\n';
output.innerText += d.toGMTString() + '\n';
output.innerText += d.toLocaleDateString() + '\n';
output.innerText += d.toUTCString() + '\n';
<pre id="output"></pre>

Upvotes: 1

Related Questions