简体   繁体   中英

How to have javascript presets today's date in HTML form

I am developing a project with Django. I have an html webpage containing a form which has a date field. I want javascript compile it with today's date as soon as my user lands on that webpage, so that he/she gets a kind of "default date".

I have in my html page (templates/aggiungi_terminologia.html), the date field:

<div class="form-group">
    <label for="glossary_entry_input_21">Data di inserimento della terminologia</label>
    <small id="inputHelp" class="form-text text-muted">Compilare solo se è nota la data di pubblicazione del documento fonte, altrimenti inserire la data di oggi.</small>
    <input name="Data_inserimento_entry" type="date" value="01/01/1900" class="form-control" id="date_to_turn_into_today" placeholder="">              
</div>

and then the javascript call at the end of the form:

{% load static %} 
<script> src="{% static 'get_today_date.js' %}"</script>

And then, inside my javascript function (static/js/get_today_date.js):

var today = moment().format('DD/MM/YYYY');
document.getElementById("date_to_turn_into_today").value = today;

and since I am using moment.js, I added 'moment' in settings.py > INSTALLED_APPS ,

and to install moment I run on my console:

pip install django-staticfiles-moment

But when I run the server, all I get on that field is this:

我的HTML表单的日期字段

My console is returning:

WARNINGS: app_glossario.glossary_entry.Data_inserimento_entry: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use django.utils.timezone.now

Why javascript is not replacing the date? How can I make it work? NOTE: the problem lies in the connection between js, html and django

Continue from comment about duplicated or not, take a look:

 var now = new Date(); var day = ("0" + now.getDate()).slice(-2); var month = ("0" + (now.getMonth() + 1)).slice(-2); var today = now.getFullYear()+"-"+(month)+"-"+(day); document.getElementById('inputDate').value = today; 
 <input type="date" id="inputDate" /> 

Please check this also.

I've seen similar behavior (where the input field shows a date placeholder instead of my desired date) when I provided a date string that was incorrectly formatted. The input element seems to need a format like yyyy-mm-dd .

Here's a pretty intuitive solution using vanilla JS. The default value of the input element will be the (locale-specific) date.

(And most of the further info you might want about JS Dates can be found here on MDN .)

 const // Selects input element dateInput = document.getElementById("date"), // Defines Date object date = new Date(), // Extracts component parts of Date object year = date.getFullYear(), month = date.getMonth(), day = date.getDate(), // Defines a function to add a leading zero if needed pad = part => part < 10 ? "0" + part : part, // Formats date to meet the `input` element's expectations -- like: `yyyy-mm-dd` // (Adds +1 to month b/c `getMonth()` uses a zero-based array) dateString = year + "-" + pad(month + 1) + "-" + pad(day); // Inserts date string into input element dateInput.defaultValue = dateString; // Repeats this process for the "time" parts /* const timeInput = document.getElementById("time"), hours = date.getHours(), minutes = date.getMinutes(), seconds = date.getSeconds(), timeString = pad(hours) + ":" + pad(minutes) + ":" + pad(seconds); timeInput.defaultValue = timeString; */ 
 <input id="date" type="date" /> <!-- // Optional input for time <input id="time" type="time" /> --> 

SOLVED

Here is what I did.

In a javascript file called

get_today_date.js

stored at path

static/js/get_today_date.js

I inserted

function get_today_date() {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day);
document.getElementById('date_to_turn_into_today').value = today;
}

as suggested here https://stackoverflow.com/a/57953522/7658051 .

Then in the HTML page, before the closing </body> tag, I inserted

{% load static %}

<script type="text/javascript" src={% static "js/get_today_date.js" %}></script>
<script> get_today_date() </script> 

and it works perfectly.

There was no neet to install the module moment, and even if my console returns

WARNINGS: app_glossario.glossary_entry.Data_inserimento_entry: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use django.utils.timezone.now

my app works fine.

The previous code did not work just because I forgot to call the function in HTML, so I just had to add

get_today_date()

But in the end I am not sure if I correctly installed the moment module required for the previuos javascript script.

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