简体   繁体   English

如何将日期从 javascript 设置为 html<input type="date"/> 元素

[英]how to set date from javascript to html <input type="date"/> element

can anyone please tell me how to set date from javascript to HTML element, Is it possible to do this because it is working with tag but not with tag , actually I have a requirement where I want a user to choose a date from one input element and it will automatically set date in another date input element with a 1-year extension.谁能告诉我如何将日期从 javascript 设置为 HTML 元素,是否可以这样做,因为它使用标签而不是标签,实际上我有一个要求,我希望用户从一个输入元素中选择一个日期它会自动在另一个日期输入元素中设置日期,并延长 1 年。

For example, if I choose a date from the first input as 02/16/2018 then it should automatically fill another date input as 02/16/2019.例如,如果我从第一个输入中选择一个日期为 02/16/2018,那么它应该自动将另一个日期输入填充为 02/16/2019。

Thanks in advance!提前致谢!

I hope this will help you.我希望这能帮到您。

 $('#field1').on('change',function(e) { $('#field2').val($(this).val()); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="date" Id="field1"/> <input type="date" Id="field2"/>

Here is the code这是代码

 const { format } = dateFns function getDate() { var oldDate = document.getElementById("oldDate").value; var date = new Date(oldDate) var newDate = new Date(date.getFullYear()+1,date.getMonth(),date.getDay()) document.getElementById("newDate").value = format(newDate, 'YYYY-MM-DD'); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.js"></script> <input type="date" onChange="getDate();" id="oldDate" /> <input type="date" id="newDate" />

I did it in an other way:我用另一种方式做到了:

 document.getElementById('1').addEventListener('change', function() { var date1 = document.getElementById('1'); var dateSplit = document.getElementById('1').value.split("-"); dateSplit[0] = parseInt(dateSplit[0]); dateSplit[0] = dateSplit[0] + 1; dateSplit[0] = dateSplit[0].toString(); var date2 = document.getElementById('2').value = dateSplit[0] + "-" + dateSplit[1] + "-" + dateSplit[2]; });
 <!doctype html> <html> <body> <input type="date" id="1"> <input type="date" id="2"> </body> </html>

您可以使用https://momentjs.com/获取所需的日期并填充$('selector').val(newdate)到另一个日期输入;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM