jQuery根据最接近的输入值在许多输入上设置不同的日期

时间:2018-08-20 12:21:51

标签: javascript jquery

我有许多日期类型的输入(每个阶段一个为初始日期,一个为新日期一个为一个新日期),而数字类型输入则应根据“最近输入的“旧日期”值。现在,它将根据第一个“旧日期”输入值更改所有日期。

function calcNewDate() {
  var addDays = parseInt($('#chdn').val());
  $('.newDate').val(formatDate(new Date($('.oldDate').val()).setDate(new Date($('.oldDate').val()).getDate() + addDays)));
}

function formatDate(date) {
  var d = new Date(date),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return [year, month, day].join('-');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Days to add to each newDate: <input id="chdn" type="number" onchange="calcNewDate();" onkeyup="calcNewDate();" />
<div class="stage">
  <h4>Stage #1</h4>
  Old date - <input class="oldDate" type="date" value="2017-06-01" disabled> New date - <input class="newDate" type="date" disabled>
</div>
<div class="stage">
  <h4>Stage #2</h4>
  Old date - <input class="oldDate" type="date" value="2017-08-15" disabled> New date - <input class="newDate" type="date" disabled>
</div>
<!-- here could be more stages -->

解决方案:

$('.newDate').each(function(){
$(this).val(formatDate(new Date($(this).prevAll('.oldDate').val()).setDate(new Date($(this).prevAll('.oldDate').val()).getDate() + parseInt($('#chdn').val()))));
});

感谢@Zenoo

1 个答案:

答案 0 :(得分:1)

由于您有多个.newDate,因此您需要遍历它们并使用jQuery .each().prevAll()方法访问每个人的.oldDate

$('.newDate').each(function(){
  $(this).val(formatDate(new Date().setDate(new Date($(this).prevAll('.oldDate').val()).getDate() + addDays)));
});

演示:

function calcNewDate() {
  const addDays = +$('#chdn').val();
  $('.newDate').each(function(){
    $(this).val(formatDate(new Date().setDate(new Date($(this).prevAll('.oldDate').val()).getDate() + addDays)));
  });
}

function formatDate(date) {
  var d = new Date(date),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return [year, month, day].join('-');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Days to add to each newDate: <input id="chdn" type="number" onchange="calcNewDate();" onkeyup="calcNewDate();" />
<div class="stage">
  <h4>Stage #1</h4>
  Old date - <input class="oldDate" type="date" value="2017-06-01" disabled> New date - <input class="newDate" type="date" disabled>
</div>
<div class="stage">
  <h4>Stage #2</h4>
  Old date - <input class="oldDate" type="date" value="2017-08-15" disabled> New date - <input class="newDate" type="date" disabled>
</div>
<!-- here could be more stages -->