Executing JavaScript - Triggering an 'onClick' event within a For loop to dynamically load multiple hyperlinks


I am currently working on creating a listview using JSON data. However, when I call an 'onclick' function from a For loop, the link opens in a new window and loads three URLs into the browser's URL input. Is there a way to modify the code below so that only one link is loaded instead of three?

            <h3>Links</h3> <br>
            <ul class="list">
                <div id="timetables"></div>
            </ul>

            <script>
            var xmlhttp = new XMLHttpRequest();
            var url = "https://api.myjson.com/bins/qg69t";
            var URL_1 = "";
            var URL_2 = "";

            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    var myArr = JSON.parse(this.responseText);
                    myFunction(myArr);
                }
            };
            xmlhttp.open("GET", url, true);
            xmlhttp.send();

            function myFunction(arr) {
                var out = "";
                var i;
                for(i = 0; i < arr.length; i++) {
                    URL_1 += arr[i].timetable_1_link;
                    URL_2 += arr[i].timetable_2_link;
                    console.log(arr[i].timetable_1_link);
                    out += '<div>' + arr[i].course + '</div><p><a href="#" onclick="openLinkInNewWindow_1()">' + arr[i].timetable_1_name + '</a></p>';
                    
                }
                document.getElementById("timetables").innerHTML = out;
            }

            function openLinkInNewWindow_1() {
                    window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
                }


            </script>

Answer №1

To enhance the function that opens the URL, you can modify it to accept a parameter in this manner:

function openLinkInNewWindow_1(URL) {
                window.open(URL, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
            }

Subsequently, when looping through the array, pass the URL as an argument with each link.

function myFunction(arr) {
            var out = "";
            var i;
            for(i = 0; i < arr.length; i++) {
                URL_1 = arr[i].timetable_1_link;
                URL_2 = arr[i].timetable_2_link;
                console.log(arr[i].timetable_1_link);
                out += '<div>' + arr[i].course + '</div><p><a href="#" onclick="openLinkInNewWindow(' + URL_1 + ')">' + arr[i].timetable_1_name + '</a></p><p><a href="#" onclick="openLinkInNewWindow(' + URL_2 + ')">' + arr[i].timetable_2_name + '</a></p>';
            }
            document.getElementById("timetables").innerHTML = out;
        }

This approach streamlines the process by utilizing only one function. Additionally, I made adjustments such as removing the trailing + from the URL_1 assignment line.

Answer №2

The issue lies in using URL_1+=. Each time the loops run, it appends a new string to the existing URL(s).

To fix this problem, remove the += from the URL_ variables in your function 'myFunction' and assign values directly using '=' only.
Below is the updated code:

<h3>Links</h3> <br>
        <ul class="list">
            <div id="timetables"></div>
        </ul>

        <script>
        var xmlhttp = new XMLHttpRequest();
        var url = "https://api.myjson.com/bins/qg69t";
        var URL_1 = "";
        var URL_2 = "";

        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var myArr = JSON.parse(this.responseText);
                myFunction(myArr);
            }
        };
        xmlhttp.open("GET", url, true);
        xmlhttp.send();

        function myFunction(arr) {
            var out = "";
            var i;
            for(i = 0; i < arr.length; i++) {
                URL_1 = arr[i].timetable_1_link;
                URL_2 = arr[i].timetable_2_link;
                out += '<div>' + arr[i].course + '</div><p><a href="#" onclick="openLinkInNewWindow_1()">' + arr[i].timetable_1_name + '</a></p><p><a href="#" onclick="openLinkInNewWindow_2()">' + arr[i].timetable_2_name + '</a></p>';
            }
            document.getElementById("timetables").innerHTML = out;
        }

        function openLinkInNewWindow_1() {
                window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
            }

        function openLinkInNewWindow_2() {
                window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
            }

        </script>

You can view the updated and active code by clicking here

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

Firestore version 9 - Retrieve nested collection depending on a string being present in an array

Working on a new chat application here. It has been a while since I last used Firestore. I am currently using v9 and facing an issue with retrieving the nested "messages" collection when the "users" array in the document contains a specific ID. I have man ...

Mastering the art of concurrent Ajax requests using jQuery for an advanced Posting and Commenting system

In my Asp.net MVC project, I have successfully implemented a post and comment mechanism. The posts and comments are stored in different tables in the database. Additionally, using Ajax requests with jQuery, I can retrieve comments from the database and dis ...

Downloading PDF files on IOS while using Angular often results in the PDF opening in the same

I'm currently utilizing file-saver within my Angular application to retrieve a PDF generated from the backend. The library functions smoothly on desktop and Android devices, but I'm encountering issues with downloading files on iOS. Contrary to w ...

Watch the Newest Vimeo Showcase Reel

I have a new project where my client is requesting to display the latest video from a specific Vimeo Portfolio. I already have a script that can fetch the latest video from the entire account using JavaScript as shown below: http://codepen.io/buschschwick ...

Accessing PUT/POST/DELETE endpoints directly from the backend through the browser without the need for UI connectivity

How can PUT/POST/DELETE methods be implemented in NodeJS directly within the browser? router.put('/sync/:syncId', (req, res) => { res.send(JSON.stringify({ "status": 200, "error": false, "response": "HELL ...

Is it truly possible to return a reactive variable that updates its value asynchronously?

While reviewing the code of a frontend project developed in Vue3, I came across a unique construction that I have not encountered before. This has led to some confusion as I try to grasp how it operates. The concept involves assigning the result of an asyn ...

transform a JSON object into a targeted JSON array

Looking to transform a JSON object into an array format, like so: [ { "name": "Batting" ,"data": [10,20,30,40]} , { "name": "Bowling" ,"data": [10,30,50,70] },{ "name": "Fielding" ,"data": [20,40,50,70]}] While I can create JSON objects for each index, I ...

Filter the array and determine the number of elements in the filtered array

I am looking to filter the contents of two arrays and then count the elements where "isimplemented: 'Yes'" is true: const array1 = [{ProjectName: "IT", Department: "Software"}] const array2 = [{Name: "IT", isimplemented: "Yes"}] The method I at ...

The ajax function does not provide a response

Can you help me figure out why this JavaScript function keeps returning 'undefined'? I really need it to return either true or false. I've included my code below: function Ajax() { var XML; if(window.XMLHttpRequest) XML=new ...

Experience real-time updates on webpages with Node.js and Socket.io

Seeking to integrate real-time push notification updates from a node.js server to the browser client. Explored socket.io at http://socket.io/docs/rooms-and-namespaces/ The business requirement involves users viewing a page with customer information and o ...

The backend is not receiving the AJAX post, which utilizes dynamically-generated JSON

I'm relatively new to Bootstrap and frontend development in general. On a page I'm working on, there's a table that displays various configurations to the user. Each row has a Change button that triggers a modal popup when clicked. Here&apos ...

I can't seem to shake off this constant error. Uncaught TypeError: Unable to access property 'classList' of null

I am facing an issue with the "Contact Me" tab as it does not display its content when clicked. Here is the code snippet: <body> <ul class="tabs"> <li data-tab-target="#home" class="active tab">Home< ...

Enhancing OpenAI API Responses with WebSocket Streaming through Express Middleware Integration

  Currently, I am in the process of developing an Express.js application that requires integration of OpenAI's streaming API responses to be transmitted in real-time to a front-end via WebSockets. Even though I have established communication between ...

What is the best approach in AngularJS for implementing a browser modal that returns a promise?

How can I implement a custom modal in my code that allows me to perform an action only after the user clicks 'okay'? var modalInstance = this.$modal.open({ templateUrl: '/app/tests/partials/markTest.html', controller: ['$sc ...

Managing and extracting specific information from a complex JSON dataset on an Android device

Scenario: I am fetching a large amount of JSON data from my backend server, specifically dealing with constantly updating movie information stored in a VPS. The initial JSON file I retrieve includes the release dates and IDs of the movies, for instance: ...

What could be causing the show button to change its style every time I click it?

I'm a beginner in the world of JavaScript. I have been working on customizing the "show more" button and encountered an issue. I managed to add text and a down arrow below the button, but when I click it, another button labeled "I don't know how ...

Is there a way to merge all this data into a single Object?

This particular situation is quite complex. Let's consider the following scenario: I have two JavaScript objects that are fetched via REST calls, using two different callbacks. So, we have: call1() - POST method - parsed JSON to JavaScript object, ...

React's Material-UI AppBar is failing to register click events

I'm experimenting with React, incorporating the AppBar and Drawer components from v0 Material-UI as functional components. I've defined the handleDrawerClick function within the class and passed it as a prop to be used as a click event in the fun ...

Swap out the image backdrop by utilizing the forward and backward buttons

I am currently working on developing a Character Selection feature for Airconsole. I had the idea of implementing this using a Jquery method similar to a Gallery. In order to achieve this, I require a previous button, a next button, and the character disp ...

The Comparison of Time Complexity between Dynamic Array Pushing and Assigning to a Fixed Size Array in JavaScript

Consider the following example with dynamic arrays: let numbersArray = []; for(let i = 0; i < 5; i++) numbersArray.push(i+1); and then we have another array: let valuesArray = Array(6); //Keep in mind that this array has a size of 6 compared t ...