Adjust time according to specified time zone using JavaScript

I am working on a project involving clocks and timezones. The user should be able to choose a timezone from a combobox, and upon selection, the main digital clock should update to display the time for that timezone. I have a text file called 'zone.txt' which contains all the timezones.
Below is an excerpt of the code I have written for this project:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clockify</title>
    <link rel="shortcut icon" href="http://cdn.onlinewebfonts.com/svg/img_461716.png">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
    <style>
        body {
            background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
            background-size: 400% 400%;
            animation: gradient 15s ease infinite;
            height: 100vh;
            font: open-sans-serif;
        }
        
        a {
            text-decoration: none;
            color: black;
        }
        
        @keyframes gradient {
            0% {
                background-position: 0% 50%;
            }
            50% {
                background-position: 100% 50%;
            }
            100% {
                background-position: 0% 50%;
            }
        }
        
        .dst-btn {
            margin-right: 75px;
        }
    </style>
</head>

<body class="unselectable">
    <div class="time-label">
        <div id="analog-clock" class="clock" style="margin-left:200px; margin-top: -180px;">
            <div class="hour">
                <div class="hr" id="hr"></div>
            </div>
            <div class="min">
                <div class="mn" id="mn"></div>
            </div>
            <div class="sec">
                <div class="sc" id="sc"></div>
            </div>
        </div>
        <div id="digital-clock" style="margin-top:-350px;"><span id="time" style="font-size:170px;font-weight:bold;color:#fff;"></span></div>
        <br><br><br>
        <div class="buttons animate__animated animate__bounceInUp" style="display: inline-block;">
            <button type="button" class="btn btn-light btn-lg dst-btn">Alarm</button>
            <select onchange="changeTimeZone();" style="padding: 10px;border-radius: 5px;padding-bottom:-2px;width:200px;" class="btn btn-light  dst-btn" name="timezone-label" id="timezone-label" aria-required="true">
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js "></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js "></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="script.js "></script>
    <script>
        // Load data from file ['Europe/Rome, Europe/Amsterdam, etc.'] into combobox
        $.ajax({
            url: 'zone.txt',
            success: function(data) {
                var splitData = data.split("\n");
                for(i = 0; i <= splitData.length; i++) {
                    $('#timezone-label').append("<option id='timezone-label' value='" + splitData[i]  + "'>" + splitData[i] + "</option>");
                }
            }
        });
    </script>
    </select>
            <button id="style" type="button" class="btn btn-light btn-lg dst-btn">Style</button>
            <button id="stopwatch" type="button " class="btn btn-light btn-lg dst-btn "><a href="stopwatch.html">Stopwatch</a></button>
            <button type="button" class="btn btn-light btn-lg dst-btn ">Countdown</button>
        </div>
    </div>
    <script>
        function changeTimeZone() {
            var timeZone = document.getElementById('timezone-label');
            const str = new Date().toLocaleString('it-IT', {
                timeZone: timeZone
            });
            var myArray = str.split(",");
            document.getElementById("time").innerHTML = myArray[1];
        }
    </script>
</body>

</html>

I have attempted to use this code, but unfortunately have encountered some issues:

        function changeTimeZone() {
        var timeZone = document.getElementById('timezone-label');
        const str = new Date().toLocaleString('it-IT', {
            timeZone: timeZone
        });
        var myArray = str.split(",");
        document.getElementById("time").innerHTML = myArray[1];
    }

In my project, I am using Bootstrap 5, jQuery, and Ajax functionalities. I suspect the problem lies with the line: timeZone: timeZone. How can I resolve this issue and properly set a timezone variable as an attribute? Upon checking the JavaScript console, I found the following error:

Uncaught RangeError: Invalid time zone specified: [object HTMLSelectElement]
at Date.toLocaleString (<anonymous>)
at changeTimeZone (clocks.html:87)
at HTMLSelectElement.onchange (clocks.html:62)

Answer №1

Current time zone is timeZone should be updated to timeZone: timeZone.value

Check it out here: Link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

From where does the require.js file originate?

Currently, I am learning Angular 2 from the tutorial available at https://github.com/pkaul/maven-typescript-example. Once I proceed with the 3rd step (mvn jetty:run), a runnable war folder is generated in the example-webapp/target directory. However, I ha ...

How can you send information to jQuery.Ajax() that will be accessible in the overarching error handler?

Here is the setup for my ajax error handler: $(document).ajaxError( handleAjaxError ); function handleAjaxError (e, jqXHR, settings, exception) { } Whenever I make a call to $.ajax(options);, I want to include a DOM element so that it can be accessed w ...

Strategies for eliminating all elements with a particular innerHTML content

function removeElements() { let li = document.getElementsByClassName("li"); for (var i = 0; i < li.length; i++) { if (li[i].innerHTML === "hello") { li[i].parentElement.remove(); } } } <li> <span class="li">hi</sp ...

Utilizing iPad, Safari, and CSS to effortlessly fill a page with flexbox properties

Trying to create a flex layout that expands the main area to fill the entire height of the display, with a footer always at the bottom when the content is small. However, if the main content exceeds the display size, it should behave like a normal page and ...

Switching from Dom to Jquery

Seeking assistance to convert DOM values into Jquery equivalent. For instance, how can I translate the DOM code: var x = document.querySelector('#x'); into Jquery format? Any suggestions? Additionally, looking for guidance on transforming even ...

It is necessary to render React Native text strings within a text component

Greetings! The React Native code snippet below is responsible for rendering a user interface. However, upon running the code, an error occurred. How can I resolve this issue? The error message indicates that text strings must be rendered within a text comp ...

Issue with Safari not displaying properly when using float:left and float:right (works fine in Firefox and Chrome)

My website has a left side column and a right side column, which display correctly in Firefox and Chrome. However, I am experiencing issues with Safari. Any insights on what could be causing this problem and why it only occurs in Safari? View the code on ...

Bug with IE lookahead in Regular Expressions

Currently, I am struggling to define the regular expression needed for proper validation in my ASP.NET validator. Although it works fine in Firefox, the sample string is not validating correctly in IE using the following expression: 12{2}12{0-9}1{12,13} ...

Next.js React Hydration Issue - "Anticipated a corresponding <a> within the server HTML <a>"

Currently, I am encountering a hydration error while working on my Next.js project. The specific error message that keeps popping up is: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected serv ...

Is there a way to customize the progress bar percentage in Ant design?

I am currently utilizing React JS and importing the Ant Design progress component (refer to https://ant.design/components/progress/). However, I am facing difficulties in dynamically editing the percentage of the progress bar using JavaScript after it has ...

Load data onto a dropdown menu using Ajax requests

My view currently includes a dropdown menu. Upon selecting an item from the dropdown, AJAX is supposed to load. The table 'locations' has a one-to-many relationship with 'contacts.' When I select a location from the locations dropdown, ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...

Adjusting the size of an HTML5 canvas using a class function when a resize event occurs

I'm attempting to adjust the size of a canvas element using a resizeCanvas() method triggered by a resize event. When I directly call the method, the canvas resizes without any issues. However, when the event handler triggers subsequent calls, I encou ...

Encountering a 404 error while using Angular HTML5Mode setting

I recently enabled pretty URLs in my Angular application by switching to html5mode. However, whenever I try to refresh the page, I encounter a 404 error. For instance, if I access my app through , everything functions as expected. But when I attempt to r ...

What is the best way to change the color of my Material Icons when I move my cursor over them?

Currently, I am integrating mui icons 5.2.0 into my React application. Although the icon appears on the page, it remains unchanged in color when I try to hover over it. Check out the snippet of code that I have implemented: import EditIcon from '@mu ...

Removing an element with delete function in jQuery without the need to refresh the page

Can anyone help me figure out how to remove an item from a page after successfully deleting it from the database using PHP and jQuery? I have a list of users and when one is deleted, I just want it removed from the page. $(document).ready(function () { ...

Introducing an alternative solution for handling tasks linked to the completion of CSS3 animations

In order to incorporate smooth CSS3 animations into my website, I have implemented the animate.css library created by Dan Eden. One particular scenario involves a loading screen that features a fade-out animation. It is crucial for this animation to comple ...

Do we need to include href in the anchor tag?

Why am I unable to display the icon within the <anchor> element without using the href attribute? The icon only appears when I set the href attribute to "". Even if I manage to show the icon by adding href="", adjusting the size with width and height ...

Using selenium in conjunction with python to click a unique button

Having trouble clicking the connect button on the "people you may know" page of LinkedIn () The HTML code for these buttons is: <a class="vcard-button bt-connect bt-primary" href="#"><span>&nbsp;</span>Connect</a> I attempted ...

Error Detected: the C# script is not compatible with Javascript and is causing

I am facing an issue where I can successfully send information from the database, but I am unable to load the table on the page. When I check the data received with an alert, it appears to be in JSON format, but it still displays the wrong image on the web ...