如何在Java Script中的两个输入选择之间按名称计算天数范围?

时间:2017-03-11 14:06:24

标签: javascript jquery

这里是一些解决方案,如何使用JavaScript计算两个选择输入之间的天数,仅使用星期名称?还是jsfiddle的一些演示?

示例:

我有两个选择标记输入:

<select>
  <option value="1">Sunday</option>
  <option value="2">Monday</option>
  <option value="3">Tuesday</option>
  <option value="4">Wednesday</option>
  <option value="5">Thursday</option>
  <option value="6">Friday</option>
  <option value="7">Saturday</option>
</select> 

 <select>
  <option value="1">Sunday</option>
  <option value="2">Monday</option>
  <option value="3">Tuesday</option>
  <option value="4">Wednesday</option>
  <option value="5">Thursday</option>
  <option value="6">Friday</option>
  <option value="7">Saturday</option>
</select> 

<input type="text" name="c_days">

如果用户在第一个中选择星期五而在第二个中选择星期一(结果为3天),则应计算第一个和第二个选择之间的总天数,并将计算的值放入c_days输入中。

感谢您的想法!

1 个答案:

答案 0 :(得分:0)

function updateResult() {
  // Get selections.
  var firstValue = parseInt(document.querySelector('#firstMenu').value);
  var secondValue = parseInt(document.querySelector('#secondMenu').value);
  // Calculate difference. If < 0, add 7 days.
  var difference = secondValue - firstValue;
  if (difference < 0) difference += 7;
  // Add value to input
  document.querySelector('#c_days').value = difference;
}

window.onload = function() {
  // Append functions to drop down menus.
  document.querySelector('#firstMenu').addEventListener('change', updateResult);
    document.querySelector('#secondMenu').addEventListener('change', updateResult);
};
<select id="firstMenu">
  <option value="1">Sunday</option>
  <option value="2">Monday</option>
  <option value="3">Tuesday</option>
  <option value="4">Wednesday</option>
  <option value="5">Thursday</option>
  <option value="6">Friday</option>
  <option value="7">Saturday</option>
</select> 

 <select id="secondMenu">
  <option value="1">Sunday</option>
  <option value="2">Monday</option>
  <option value="3">Tuesday</option>
  <option value="4">Wednesday</option>
  <option value="5">Thursday</option>
  <option value="6">Friday</option>
  <option value="7">Saturday</option>
</select> 

<input type="text" name="c_days" id="c_days" value="0">