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

"Empowering your scripting skills with PowerShell to manipulate JSON data

Greetings everyone, I have been executing a ReST api call in PowerShell and received the following response: $response page content ---- ------- @{size=20; numbe ...

Retrieving live information from an API in order to populate a specific route

Utilizing the contents of two crucial files to extract data from separate APIs, here is my simplified example: poloniex.js const Poloniex = require('poloniex-api-node') const poloniex = new Poloniex() async function obtainExchangeData() { po ...

How to retrieve the current event handler's value with jQuery

To assign an onclick event handler using jQuery, I simply use the following code: $('#id').click(function(){ console.log('click!'); }); Now, my question is how can I retrieve a reference to the function that is currently handling th ...

Change the right border style for the second and third ToggleButtons in the ToggleButtonGroup

I've been working on this for a few hours now and I can't seem to get it right. Currently, I'm using Mui v5 and trying to style the ToggleButtons to look like regular MUI buttons. So far, I was able to achieve this transformation: https:/ ...

Issues with Angular functionality

I'm a newcomer to Angular and I am trying to recreate this example from jsfiddle in order to experiment with nodes. However, I am encountering issues with the Angular setup. Firstly, the jsfiddle is causing confusion because the application names do n ...

What is the best way to compare two JSON strings in a Flutter application?

Need help comparing two lengthy JSON strings to determine if they are equal or not. If they are not equal, I want to create list1 with the differences between JSON1 and JSON2, and list2 with the differences between JSON2 and JSON1. I came across this libr ...

Reverting HTML entities in Json to their original characters

Issue and initial data In my json dataset, there are HTML entities used to encode special French characters like “é”, “ç”, “à”, etc., as well as html tags. Here is a snippet of the json data: { "data1": "&lt;p&gt; ...

What is the process of querying both a collection and a subcollection in Firebase using AngularFire?

I have a structure in my firebase database that looks like this: /profiles/{uid}/displayName /email /otherAttribues /roles/{roleName}/someAttribute /someOtherAttribute The reason ...

After the component has been initialized for the second time, the elementId is found to be null

When working with a component that involves drawing a canvas chart, I encountered an issue. Upon initializing the component for the first time, everything works fine. However, if I navigate away from the component and return to it later, document.getElemen ...

Looking to switch up the thumbs-up button design?

I am a beginner in using jquery and ajax, and I need some assistance. How can I incorporate this jquery code into my logic: $('.btn-likes').on('click', function() { $(this).toggleClass('liked'); }); Can so ...

The gear icon in the video player is not showing up when I try to change the

I am currently trying to implement a feature that allows users to select the quality of the video. I am using videojs along with the videojs-quality-selector plugin, but even though the video runs successfully, the option to choose the quality is not appea ...

Retrieving metadata using breeze is taking too long

Using breeze in my MVC 4 application to fetch data from a remote SQL Server database with about 40 entities. Surprisingly, the loading of metadata is taking longer than expected, ranging between 14s and 35s even though the size is just around 600kb. Howev ...

Laravel: The current configuration does not support the experimental syntax 'classProperties' at this time

When compiling my javascript files using npm run dev, I encountered a warning in my resource/app.js file where I require my custom validation script. The warning stated the following: Module build failed (from ./node_modules/babel-loader/lib/index.js): Syn ...

What is the best way to calculate the total number of results using ajax?

Encountering an issue with the total count of ajax search results. Getting an error message "Method Illuminate\Database\Eloquent\Collection::total does not exist." when using directives, for example: <div class="searched-item"&g ...

Switch Your PHP Script to Use PDO

Hello, I am new to PHP and seeking some guidance. My goal is to convert the following code to PDO in order to generate a JSON output for an Android app that I am currently working on. I have tried several solutions but encountered issues with the JSON resp ...

Utilize Hardhat and NPM to distinguish between unit tests and integration tests efficiently

Struggling with setting up two commands in my package.json for running unit tests and integration tests. I am having trouble defining the location of the testset for each type of testing. Within the scripts section of my package.json, I have created two c ...

Creating an object using JSON data?

Currently, I am in the process of creating a City class that will be populated with JSON data retrieved from a server. public class City { public string id { get; set; } public string country { get; set; } public string region { get; set; } ...

AngularJS: ng-show causing flickering issue upon page refresh

Recently, I encountered an issue with my code snippet: <body> <ng-view></ng-view> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script> <script src="http://ajax.googleapis.com/ajax/ ...

Parsing JSON Data in Python

I am currently working with a json document called as_stats.json. Here is an example of what the contents may look like: {"failed":5, "received": {"192.168.5.2": 40, "192.168.5.45": 84, "127.0.0.1": 145}} Below is a snippet of my python code that parses ...

Learn how to upload an image from Express.js to Google Cloud Storage or Firebase Storage

Currently, I am delving into the world of ExpressJS and attempting to upload an image to Firebase storage using Node. However, I encountered the error message: firebase.storage().ref() is not a function. After researching this issue, I stumbled upon this ...