Rio Gonchar
Rio Gonchar

Reputation: 11

How to update selected option value using Java Script

I am trying to add extra 5 minutes to the users input. In other word; if the user selects 8:00 am from the drop down; the result should be 8:05 am. I tried doing it with a string (example below) and it works. However - I am wondering if there is a way to convert the value of the time automatically and pass it to the result.

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>

Upvotes: 0

Views: 203

Answers (2)

Raya Nasiri
Raya Nasiri

Reputation: 151

an easy way to do this:

<select id="mySelect">
  <option value="8:05 AM">8:00 am</option>
  <option value="9:05 AM">9: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>

Upvotes: 1

brk
brk

Reputation: 50336

You can create a function & convert the selected hours to mins and add 5 mins to it.THen convert it back to hrs and mins

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>

Upvotes: 0

Related Questions