-1

Get time based on selected timezone :

I have a JS function that takes a time zone as an argument and returns the current time in that time zone.

function worldClock(zone) {
    var time = new Date()
    var gmtMS = time.getTime() + (time.getTimezoneOffset() * 60000)
    var gmtTime = new Date(gmtMS)

    var hr = gmtTime.getHours() + zone
    var min = gmtTime.getMinutes()
    var sec = gmtTime.getSeconds()

    if (hr < 10){
    hr = "0" + hr
    }
    if (min < 10){
    min = "0" + min
    }
    if (sec < 10){
    sec = "0" + sec
    }
    return hr + ":" + min + ":" + sec;
};

I also have a dropdown list with a list of cities and their time zone as a value.

 <select name="city">
        <option value="-4">Toronto</option>
        <option value="2">Stokholm</option>
        <option value="-5">New-York</option>
      </select>

I need the worldClock () function to be called when a certain city is selected; pass the value from the dropdown list as an argument and display the resulting value and city name: Toronto: 04:52:16; How can this be implemented?

2
  • 1
    add an event listener on the select, when it changes. get the selected option and pass the value to the function Commented Oct 25, 2018 at 8:54
  • 1
    Shortest simplest way: <select name="city" onchange="worldClock(this.value);"> . I'm surprised you couldn't find that out with a very quick bit of research though. Handling the selection of an option from a dropdown is a very common requirement, you would have found an example after a few moments. If you want a slightly more up-to-date way of doing things, look into Unobtrusive Event Handlers Commented Oct 25, 2018 at 8:54

1 Answer 1

0

Add Onchange event:

function worldClock(zone) {
    var time = new Date()
    var gmtMS = time.getTime() + (time.getTimezoneOffset() * 60000)
    var gmtTime = new Date(gmtMS)

    var hr = gmtTime.getHours() + zone
    var min = gmtTime.getMinutes()
    var sec = gmtTime.getSeconds()

    if (hr < 10){
    hr = "0" + hr
    }
    if (min < 10){
    min = "0" + min
    }
    if (sec < 10){
    sec = "0" + sec
    }
    var output= hr + ":" + min + ":" + sec;
    console.log(output);
    return output;
};
 <select name="city" onchange="worldClock(this.value);">
        <option value="-4">Toronto</option>
        <option value="2">Stokholm</option>
        <option value="-5">New-York</option>
      </select>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.