jz22
jz22

Reputation: 2638

Setting variables in a href link in html

I have around 50 links to rendered dashboards that are quite different from each other. But all have two attributes. A from and a to attribute. They define a time frame with a start and an end date.

For each of the around 50 links there is a html tag in the body and the links themselves are the href attributes. Please take this as an example:

<a id="id1" download="picture.png" href="https://url.com/render/dashboard-solo/db/dashboardname?panelId=5&from=01012017&to=04012017&width=1000&height=50"/>

Now I need two input fields that allow me to set the dates. For instance if I type in 02022017 in the input field for the from attribute I want a javascript to replace all the from attributes in the hrefs of the tags in the body with that input value.

I have like 50 lines that look like the example above but they are have a different url. They also have different dashboard names and panel IDs.

Do you have an idea? Of course I can set up a javascript and two input forms but I don't know how to set an href attribute partly as variable. Thanks

Upvotes: 0

Views: 8103

Answers (1)

Jamiec
Jamiec

Reputation: 136104

I think you're going about this all wrong. You dont want to update all the href attributes on all those links, you want to call a javascript function on click of each of them and make it navigate to a specific url with a variable from/to attribute.

Take a look at this example:

function goToDashboard(panelId){
    var fromValue = document.getElementById("from").value;
    var toValue = document.getElementById("to").value;
    var uri = "https://url.com/render/dashboard-solo/db/dashboardname?panelId=" + panelId + "&from=" + fromValue + "&to=" + toValue + "&width=1000&height=50";
    console.log(uri);
    return false;
}
<a id="id1" download="picture.png" href="#" onClick="return goToDashboard(5)">Go to dashboard</a>

<hr>
From: <input id="from" value="01012017">
To: <input id="to" value="04012017">

If you simply change that console.log(uri) to location.href=uri it will work exactly like a link, but now from and to are dynamic.


It seems you need to actually set the href attribute. This is do-able too.

function goToDashboard(link, panelId){
    var fromValue = document.getElementById("from").value;
    var toValue = document.getElementById("to").value;
    var uri = "https://url.com/render/dashboard-solo/db/dashboardname?panelId=" + panelId + "&from=" + fromValue + "&to=" + toValue + "&width=1000&height=50";
    link.setAttribute("href",uri);
    link.click();
    return false;
}
<a id="id1" download="picture.png" href="#" onClick="return goToDashboard(this, 5)">Go to dashboard</a>

<hr>
From: <input id="from" value="01012017">
To: <input id="to" value="04012017">

Upvotes: 1

Related Questions