简体   繁体   English

如何使用jQuery添加日期

[英]How to add days to date using jQuery

I have input text like below: 我输入的文字如下:

 $('#term').change(function() { var ll = $(this).val(); var bb = $('#date').val(); var date = new Date(bb); var newDate = new Date(date); newDate.setDate(newDate.getDate() + parseInt(ll)); var dd = newDate.getDate(); var mm = newDate.getMonth() + 1; var y = newDate.getFullYear(); var someFormattedDate = dd + '-' + mm + '-' + y; $('#due_date').val(someFormattedDate); }); 
 div { margin: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <label for="date">Date:</label> <input id="invodate" type="text" id="date" class="form-control" name="date" value="" style="width: 150px;"> </div> <div class="form-group"> <label for="term">Term:</label> <input type="text" class="form-control" id="term" name="term" value="" style="width: 50px;"> </div> <div class="form-group"> <label for="due_date">Due Date:</label> <input type="text" class="form-control" id="due_date" name="due_date" value="" style="width: 150px;"> </div> 

I wanna give days to input #term and then on Due Date in input show date, but in my code show NaN-NaN-NaN only. 我想input #term ,然后输入显示日期作为到期日,但在我的代码中仅显示NaN-NaN-NaN What error with my code. 我的代码有什么错误。 thank for answer. 感谢您的回答。

Your first input has two ID's, which is invalid, and you're passing a date object to the Date constructor. 您的第一个输入有两个ID,这是无效的,并且您要将一个date对象传递给Date构造函数。

This is quite simple with plain javascript 使用普通的javascript,这非常简单

 $('#term').change(function() { var ll = $(this).val(); var bb = $('#date').val(); var date = new Date(bb); date.setDate(date.getDate() + (+ll)); var dd = date.getDate(); var mm = date.getMonth() + 1; var y = date.getFullYear(); var someFormattedDate = dd + '-' + mm + '-' + y; $('#due_date').val(someFormattedDate); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <label for="date">Date:</label> <input type="text" id="date" class="form-control" name="date" value="05-05-2017" style="width: 150px;"> </div> <div class="form-group"> <label for="term">Term:</label> <input type="text" class="form-control" id="term" name="term" value="" placeholder="type here" style="width: 50px;"> </div> <div class="form-group"> <label for="due_date">Due Date:</label> <input type="text" class="form-control" id="due_date" name="due_date" value="" style="width: 150px;"> </div> 

Nan (Not a number) getDate function does not return integer. Nan(非数字)getDate函数不返回整数。 Object + 11 is not a valid operation (most of the time!). 对象+ 11不是有效的操作(大多数情况下!)。

You can use Datejs mentioned here 您可以使用Datejs提到这里

var duedate = new Date.today().addDays(11); 

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

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