kieran_mol kieran_mol - 1 year ago 37
Javascript Question

JavaScript - Calling an 'onClick' function from a For loop loading multiple links



I am in the process of creating a listview from JSON data however, after calling an 'onclick' function from a For loop, the link, which opens up in a new window, loads three URLs into the URL input of the browser. Any idea how I could re-work the below code to just load one link rather that the three based on the below 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;
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><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>

Answer Source

You can start by refactoring the function that opens the URL to accept a parameter like this:

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

Then in the for loop pass the URL along 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 way you only need the one function. Notice also that I removed the + from the URL_1 += line.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download