如何使用Java Script更新选定的选项值

时间:2018-05-20 07:30:07

标签: javascript html

我正在尝试为用户输入添加额外的5分钟。换句话说;如果用户从下拉菜单中选择上午8点;结果应该是早上8:05。我尝试用字符串(下面的例子)来做它并且它有效。但是 - 我想知道是否有办法自动转换时间值并将其传递给结果。



function myFunction() {
  var time = document.getElementById("mySelect").value;
  document.getElementById("result").innerHTML = "8:05 AM";
}

<select id="mySelect">
  <option>8:00 am</option>
</select>

<button onclick="myFunction()">Get Result with extra 5min</button>

<p id="result"></p>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

一种简单的方法:

<select id="mySelect">
  <option value="8:05 AM">8:00 am</option>
</select>

<button onclick="myFunction()">Get Result with extra 5min</button>

<p id="result"></p>

<script>
  function myFunction() {
  var time = document.getElementById("mySelect").value;
  document.getElementById("result").innerHTML = time;
}
</script>

答案 1 :(得分:0)

你可以创建一个功能&amp;将选定的小时数转换为分钟,然后再添加5分钟。将其转换回小时和分钟

function myFunction() {
  var time = document.getElementById("mySelect").value;
  // split will create an array from value of the options for example
  // 8:00:am will be [8,00,am]
  let splitNum = time.split(":");
  // converting  hrs hrs to mins
  // parseInt to convert string to number
  // adding 5 mins to the calculation
  let convertToMin = parseInt(splitNum[0], 10) * 60 + parseInt(splitNum[1], 10) + 5;
  // Math.floor will give the hrs
  let convertBackHrs = Math.floor(convertToMin / 60);
  // getting the minutes
  let getMins = (convertToMin - convertBackHrs * 60)
  if (getMins < 10) {
    // if minutes is less than 10 for example then add a 0 before it
    getMins = "0" + getMins
  }
  document.getElementById("result").innerHTML = convertBackHrs + ":" + getMins + splitNum[2];
}
<select id="mySelect">
  <option value="8:00:am">8:00 am</option>
  <option value="8:58:pm">8:58 am</option>
  <option value="1:58:pm">1:58 pm</option>
  <option value="2:00:pm">2.00 pm</option>
</select>

<button onclick="myFunction()">Get Result with extra 5min</button>

<p id="result"></p>