Using a variable as the href - javascript

I want to have the href consist of a variable set in javascript, I also need the text that is displayed on the page to be a variable. In the example below I would like to have the string "http://google.com" be assigned to a variable, I also need to have "My Link Name" as a variable. I have looked at similar questions here but I don't see what addresses this particular situation.
Go Here Now<br>
In the example below I can create a variable called myLinkName and set it to the string "Go here now" however I don't know how to create a variable and set it to the value of the href e.g. "http://google.com"
<script type="text/javascript">
var myLinkName = "Go Here Now";
</script>
<a href="http://google.com">
<script type="text/javascript">
document.write(myLinkName)
</script></a>

You have to use the DOM API
HTML
<a id="aLink"></a>
Javascript
let link = document.getElementById('aLink');
link.href = "https://google.com";
link.innerText = 'This is my Link'
The complete code:
<html>
<body>
<a id="aLink"></a>
<script>
let link = document.getElementById('aLink');
link.href = "https://google.com";
link.innerText = 'This is Link';
</script>
</body>
</html>

I fear you are using some very old JavaScript material.
The usage of document.write() is depricated.
The approach you are following is antiqated. Today JS is not evaluated and just written to the document. Instead the document is explicitly manipulated.
First of all: <script> is sufficient to declare some JavaScript. The type attribute is not needed anymore.
<a id=myLink></a>
<script>
//get a reference to the a element
const myLink = document.getElementById("myLink");
//set the text
myLink.innerText = "Click me!";
//set href
myLink.href = "http://google.com";
</script>

You can set href attribute like this
var text = 'Go Here Now';
var href = 'http://google.com'
var atag = document.getElementsByTagName('a')[0];
atag.innerText = text;
atag.href = href;
var text = 'Go Here Now';
var href = 'http://google.com'
var atag = document.getElementsByTagName('a')[0];
atag.innerText = text;
atag.href = href;
<br>

I would create an object that contains your link name and href and on page load, assign accordingly. Something like:
window.addEventListener('load', function(){
var link = {
name : 'My Link Name',
href : 'http://google.com' //should use : instead of =
};
var myLink = document.getElementByTagName('a')[0]; //You would change this to whatever selector you want.
myLink.innerText(link.name);
myLink.setAttribute('href', link.href);
}, true);
Syntax may not be perfect. And, depending on your situation, it may be better to accomplish this with your server side code. Hope this helps!

You can change the href attribute by doing this:
<a href="http://google.com" id="link">
<script type="text/javascript">
var yourtext = 'Go Here Now';
var href = 'http://google.com';
document.getElementById('link').href = myLinkName;
document.getElementById('link').innerText = yourtext;
</script></a>

By using JQuery we can update/add href to the element like below.
HTML code:
Click Here
JQuery code:
$("#linkId").attr("href", "http://www.google.com/'");

Related

How to Bind Jquery Value to an HTML Element

How can i bind the url result from the jquery to the href ? as you can see on the html below. Thank you.
JQUERY CODE
<script>
$(document).ready(function(){
$("#btnSearch").click(function(){
var yearArray = [];
$("input:checkbox[name=Year]:checked").each(function(){
yearArray.push($(this).val());
});
var makeArray = [];
$("input:checkbox[name=Make]:checked").each(function(){
makeArray.push($(this).val());
});
var url="http://example.com/results?Year="+yearArray.join()+"&Model="+makeArray.join();
alert(url);
});
});
</script>
HTML
<a href="/searchnew/{{ url }}"><button id="btnSearch" class="btn btn-cta margin-bottom-1x search-button cssBase"
type="button""
style="width: 262.5px;">Search</button></a>
You can simpy add href attribute after creating link. What i mean by this is
if your href tag is look like this
<a href="#" id="myurl">
$("#myurl").prop("href",url);
This will simply render your html like this
<a href="http://example.com/results?Year="......(your dynamic values here)">
You don't have to add tag on to button click. Instead, on click of button, within the function after you have prepared url, call
location.href = "searchnew/" + url;
In case you have the base url for the app, you can prepend as well to have the complete url with you.
Use id attribute for your a tag like this-
<a href="....." id="myLink" > ... </a>
And at the end of your jQuery code add the following:
var a = $('#myLink');
var href = a.attr('href');
a.attr('href', href + url);

How to display result of javascript as HTML link?

I have the following code that I use to retrieve the hostname of a server and append some text (a filename) to it and display it on an html page.
<script type="text/javascript">
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
<script type="text/javascript">
document.write(getBaseUrl() + "filename.ext");
</script>
That generates a server URL such as https://fqdn/folder/filename.ext which is exactly what I need. Everything I have tried to create a link from it breaks things. How do I make that generated text clickable?
It's pretty straight forward to do -
const link = getBaseUrl()+ "filename.ext";
createLinkNode(link, document.body);
// defining a function to create a link node, however this isn't neccessary,
// you could just hard code the logic above.
// I wouldn't recommend setting innerHtml in lieu of making a text node however.
function createLinkNode(url, parent) {
const linkTextNode = document.createTextNode(url);
const linkNode = document.createElement('a');
linkNode.href = url;
linkNode.appendChild(linkTextNode);
parent.appendChild(linkNode);
}
example: https://jsfiddle.net/f4wxvLky/3/
You'd need to wrap it in an <a href=''></a>. This is easiest if you assign the <a> element in question to a variable, as you can then use .href to modify the link, along with .innerHTML to modify the text:
function getBaseUrl() {
return 'http://www.google.com/';
}
const output = document.getElementById('output');
output.innerHTML = 'Link Title';
output.href = getBaseUrl() + "filename.ext";
<a id="output" href=""></a>
If you don't have access to the HTML, this can still be done with raw JavaScript by simply including the <a href=''></a> wrapper in your output, being careful to also output the single quotes:
function getBaseUrl() {
return 'http://www.google.com/';
}
document.write("<a href='" + getBaseUrl() + "filename.ext" + "'>Link Title</a>");
Try this out, I assume getBaseUrl() is working although this doesn't look like. Just a reminder that <a> tag needs to be under the <script> block
<script>
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
Click

Change href of <a> element using javascript

Please, code to change domain in href (html, JavaScript).
Exemple:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
To:
<a id="NewL" href="http://exemple.net/indice.html">Indice</a>
Exemple code not working:
<script type = "text/javascript" >
function replace() {
var aEls = document.getElementById('NewL').getElementsByTagName('a');
aEls.href = aEls.href.replace('http://exemple\.com', 'http://exemple\.net');
}
</script>
Thanks, #t.niese:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
<script type="text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
}
replace();
</script>
Please help me, not change in various ID in same page:
<a id="NewL" href="http://exemple.com/indice.html">Indice</a>
<a id="NewL" href="http://exemple.com/indice2.html">Indice 2</a>
<script type="text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('http://exemple.com', 'http://exemple.net');
}
replace();
</script>
Element.getElementsByTagName():
[...]The subtree underneath the specified element is searched, excluding the element itself.[...]
so you search for the elements with the tag name a within your element with the id NewL
Because document.getElementById('NewL') is already your a element, you won't need the getElementsByTagName('a'), as of that you should only write:
var aEl = document.getElementById('NewL');
Also your replace is wrong, you don't need to escape the . if you pass the search as string.
aEl.href = aEl.href.replace('htp://exemple.com', 'htp://exemple.net');
Beside that Element.getElementsByTagName() returns a list of elements, so even if your search would have been correct, you would need to use a loop to iterate through that result.
change your javascript to the following:
<script type = "text/javascript" >
function replace() {
var aEl = document.getElementById('NewL');
aEl.href = aEl.href.replace('htp://exemple\.com', 'htp://exemple\.net');
}
</script>
You already selected the element by the getElementById no need to find the a class in it. Also you mispelled the variable which I changed to aEl

how to echo javascript generated value in href?

This is my javascript code below (Just to get current url)
<html>
<head>
</head>
<body onload="myFunction();">
<p id="myurl"></p>
<script>
function myFunction() {
document.getElementById("myurl").innerHTML =
window.location.host;
}
</script>
</body>
</html>
And Now i want to use <p id="myurl"></p> as below:
</p>">Share on Facebook <br>
But as it cant be execured inside href="value"
Is there any way to do that with php or something else?
Use this :-
Share on Facebook <br>
With pure javascript (default url in href):
<a id="share_url" href="https://www.facebook.com/sharer/sharer.php?u=">Share on Facebook</a>
<script>
function myFunction() {
var el = document.getElementById("share_url");
el.href += window.location.host;
}
</script>
Demo: http://jsfiddle.net/Lrkjr23o/1/
Other way to create href attribute dynamically:
<a id="share_url">Share on Facebook</a>
<script>
function myFunction() {
var el = document.getElementById("share_url");
el.href = 'https://www.facebook.com/sharer/sharer.php?u=';
el.href += window.location.host;
}
</script>
Demo: http://jsfiddle.net/Lrkjr23o/
I'm assuming client only solution is needed here, server can be anything (PHP, ASP, etc.)
All you've to do is to modify the href property of anchor tag. You can modify your code as -
var elm = document.getElementById("demo");
var URLBase = elm.getAttribute("href");
var fullURL = URLBase.window.location.host;
elm.setAttribute("href", fullURL);

Adding javascript variable to hyperlink within script

I have been trying to create a hyperlink using a variable defined earlier in the same function to append:
var NAMEVARIABLE = responseArray[i].Name;
var TITLE_Game = document.createElement("p");
TITLE_Game.className = "TITLE_Game";
TITLE_Game.innerHTML = "<a href='Game_NAMEVARIABLE.html'>Games</a>";
I have tried the following using the solution found here: Passing Javascript variable to <a href >
Games
But that didn't work. I then tried adding an ID:
<a id="link" href="Game_.html?propid=">Games</a>
And adding this to the script: document.links["link"].href += NAMEVARIABLE;
This didn't work either. These links are occuring within Isotope, which I've run into newbie-problems making sure my JSON data is loading before the script executes. That's all working now, but I'm not sure if the reason the above methods aren't working is because of a similar issue, or if they simply are not the proper way to go about this.
Any help is much appreciated. Thank you
first of all, try debug your variable :
var NAMEVARIABLE = responseArray[i].Name;
alert(NAMEVARIABLE);
is it returning the desired return value or not.
and then the second thing, in your first style of script, try this instead :
TITLE_Game.innerHTML = "<a href='Game_"+NAMEVARIABLE+".html'>Games</a>";
I assumed you have (static) html collection with game_[number_id].html format
and if it's so, you can try further with your second style of script, and change it to this :
Games
you need to learn further about javascript strings concatenation
Use string concatenation to build up your inner html string.
Example:
var nameVariable = 'Foo';
var innerHtmlText = nameVariable + 'bar';
$('#someElement').html(innerHtmlText);
The contents of someElement will then contain the text: 'Foobar';
You just need string concatenation. modify link's href onclick would be considered as spam in most modern browser.
<div id="result">
the result:
</div>
<script type="text/javascript">
var name = "foo_bar";
var url = "page.html?key=" + name; //or.. "page_" + name + ".html";
var link = 'link here';
$("#result").addClass("g_title");
$("#result").append(link);
</script>
This can be achieved by either (i.e. pure JS or jQuery) ways without much hassle. Suppose you have this <a> element with some href
<a id="Link" href="/collection/categories/">Games</a>
Pure JavaScript way:
window.onload = function() {
var link= document.getElementById('Link'),
url = link.href + responseArray[i].Name + '.html';
link.setAttribute('href', url);
}
Using Jquery:
$(function(){
var link= $('#Link'),
url = link.attr('href') + responseArray[i].Name + '.html';
link.attr('href', url);
});

Categories

Resources