How can I display a href link inside an if condition using javascript?
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
var x = document.getElementById("fname");
if(x.value.indexOf("aaaa")>=0)document.getElementById("result").innerHTML= ""+ x.value + "" ;
else document.getElementById("result").innerHTML=x.value;
}
</script>
<form method="post" action="esegui.php">
Name<br><input type="text" id="fname" onkeyup="myFunction()">
</form>
<p id="result"></p>
</body>
</html>
You can create anchor tag using JavaScript following way:
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://www.google.com");
aTag.innerHTML = "aaa";
document.body.appendChild(aTag);
Put above code in if condition will create anchor tag(link).
Although your question is a little bit confusing, I'll try to help you
If what you want is to create a specific link, do this:
var link = window.document.createElement("a");
var str = window.document.getElementById("theidofyourinput").value;
link.textContent = str;
link.href = 'http://www.linkofyourpage';
document.getElementsByTagName('body')[0].appendChild(link);
Try researching the createElement() method in JavaScript, calling it to create an anchor element in the body of your if statement e.g.
var myLink = document.createElement('a');
myLink.appendChild(document.createTextNode('link name')); //visible text
myLink.setAttribute('href', 'http://google.com'); //link href attribute
document.getElementById('someId').appendChild(myLink); //append the element
There are many ways to do this but you have not mentioned specific scenario so do like this:
In HTML:
<div id="test"></div>
In Java script:
var markup = "link";
var v = document.getElementById("test") ;
v.innerHtml(v );
Related
How to put JavaScript value inside HTML ?
I am trying to put JavaScript value inside HTML like below.
<p>
Check your Credit Score Here
</p>
To achieve the results, you can make use of document.getElementById('').href property:
HTML (added the id attribute to the <a> tag):
<p>
Check your Credit Score <a id="link" href="" target="_blank">Here</a>
</p>
JavaScript:
window.onload = function() {
var first_name = 'Peter';
document.getElementById('link').href = 'http://someaddress.com?first_name='+ first_name;
// debug your results
console.log(document.getElementById('link').href);
}
Here is the JSFiddle
do this if you want to change the link
document.querySelector('a').href = "http://someaddress.com?first_name=" + first_name;
You can do like this
<p>
Check your Credit Score
<a href="http://someaddress.com?first_name='+ first_name +'" target="_blank"
>Here</a >
</p>
<script type="text/javascript">
const a = document.querySelector('a');
const first_name = 'John';
a.href = 'http://someaddress.com?first_name=' + first_name ;
</script>
For best practice do an if check otherwise your selector might not be found in the dom.
Also, if in querySelector("...anything...") not querySelector("a") is given the editor won't suggest the href prop that exists or not. Hence, setAttribute makes more sense.
const URL = "http://someaddress.com?first_name="
const name = 'adiat'
const anchor = document.querySelector(".what-ever")
if(anchor){
anchor.setAttribute("href", `${URL}${name}`);
}else{
console.warn("element not found to replace href attribute")
}
// shorthand -> anchor?.setAttribute("href", `${URL}${name}`);
A robust way would be to use a token to replace, I've used {{FirstName}}. Use an attribute selector to select via that token then replace that token on the href attribute
let firstNameLinks = document.querySelectorAll("a[href*='{{FirstName}}'");
let firstName = "Bob";
for(i = 0; i < firstNameLinks.length; i++){
console.log(firstNameLinks[i].href)
firstNameLinks[i].href = firstNameLinks[i].href.replace("{{FirstName}}", firstName);
}
A link
Another link
create a hyperlink with the variable link
<html>
<body>
<center><h1> retrive data</h1></center>
<h1 id="head1"> </h1>
<input type="text" placeholder="enter your unique id" id="pass"/>
<input type = "button" value = "submit" id="but" onclick="myfunction();"/>
<script>
var pass;
function myfunction()
{
pass = document.getElementById("pass").value;
document.writeln(pass);
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
var passwordToLookFor = pass;
var ref = firebase.database().ref("users");
var query = ref.orderByChild("password").equalTo(passwordToLookFor);
query.once("value").then(function(snapshot) {
snapshot.forEach(function(child) { // loop over the results
console.log(child.key);
console.log(child.val().user_name);
var link = child.val().user_name;
document.writeln(link);
});
});
}
</script>
</body></html>
i want to create the value of link as a hyperlink
i want the hyperlink to be created once when the function is called
Are you just looking for how to make it an anchor tag?
<script>
var pass;
function myfunction()
{
...
var link = child.val().user_name;
document.writeln("<a href='"+link+"' target='_blank'>"+link+"</a>");
});
});
}
</script>
</body></html>
You can create an a dom element like this:
let link_el = document.createElement('a')
link_el.href = link // assuming link holds the value of the href you want
Then insert it into the dom wherever you want.
If I understand correctly and the link variable contains the actual address you want to navigate to, then this will work. First simply set an ID on the div you want to populate with links:
<div id="target-div"></div>
Then populate it like so (I just created an array for demo purposes, but this would be your snapshot.forEach:
var links = ['link1', 'link2', 'link3']
var targetDiv = document.getElementById("target-div");
links.forEach(function(link) {
var anchor = document.createElement('a');
anchor.href = link;
anchor.innerText = link;
targetDiv.appendChild(anchor);
var br = document.createElement('br');
targetDiv.appendChild(br);
});
Demo: https://jsfiddle.net/csnuh7rd/2/
In some part of an html page, I have a link with the following code :
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
I would like to automatically display the same link in another part of the same page by using a javascript.
What would be the script to insert in my page ?
Thank you in advance for any help in this matter.
Patrick
Try this:
myVar = document.getElementById("idname");
varLink = (myVar.attributes.href);
As son as you know the target id:
<div id="targetID">New Link: </div>
<div id="targetID2">New Link 2: </div>
And If you are using jQuery you can do like this:
var link = $("#idname").clone();
link.attr("id",link.attr("id") + (Math.random() * 10));
$("#targetID").append(link);
If not:
var link = document.getElementById("idname");
var newLink = document.createElement("a");
newLink.href = link.href;
newLink.className = link.className;
newLink.innerHTML = link.innerHTML;
newLink.id = link.id + (Math.random() * 10);
document.getElementById("targetID2").appendChild(newLink);
See this Example
<script>
window.onload = function() {
// get data from link we want to copy
var aHref = document.getElementById('idname').href;
var aText = document.getElementById('idname').innerHTML;
// create new link element with data above
var a = document.createElement('a');
a.innerHTML = aText;
a.href = aHref;
// paste our link to needed place
var placeToCopy = document.getElementById('anotherplace');
placeToCopy.appendChild(a);
}
</script>
Use code above, if you want just to copy your link to another place. JSFiddle
First, I want to point out that if you will just copy the element that will throw an error because the copied element will have the same id of the first one, so if you will create a copy of your element you don't have to give it the same id.
Try this code:
function copyLink(newDestination){
var dest=document.getElementById(newDestination);
var newLink=document.createElement("a");
var myLink=document.getElementsByClassName("classname")[0];
newLink.href=myLink.href;
newLink.className = myLink.className;
newLink.innerHTML = myLink.innerHTML;
newDestination.appendChild(newLink);
}
The newDestination parameter is the container element of the new Link.
For example if the new Container element has the id "div1":
window.onload = function() {
copyLink(div1);
}
Here's a DEMO.
Thank you very much to everyone for so many prompt replies.
Finally, I was able to use Jquery.
So, I tried the solution given by Andrew Lancaster.
In my page, I added the codes as follows, in this order :
1-
<span id="span1">
<a class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
and further down the page :
2-
<script type="text/javascript">
var span1val = $('#span1').html();
$('#span2').html(span1val);
</script>
Therefore, the two expected identical links are properly displayed.
But, unfortunately, I forgot to say something in my initial request:
the original link is in the bottom part of my page
I would like to have the duplicated link in a upper part of my page
So, would you know how to have the duplicated link above the original link ?
By the way, to solve the invalid markup mentioned by David, I just deleted id="idname" from the original link (that I could ignored or replaced by other means).
Thank you again in advance for any new reply.
Patrick
Using Jquery you could wrap your link in a span with an ID and then get the value of that ID and push it into another span id.
HTML
<span id="span1">
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
jQuery
var span1val = $('#span1').html();
$('#span2').html(span1val);
Example can be found here.
http://jsfiddle.net/3en2Lgmu/5/
Part of my code:
<p id="demo">{$value.file_name}</p>
<script type="text/javascript">
var str = document.getElementById("demo").innerHTML;
var res = str.replace("/var/www/html/biology/demo", "");
document.getElementById('para').innerHTML = res;
</script>
<a href="#para" id='para'>Download</a>
This part of the url will already be present: "a.b.c.d.edu/bio/cluster/"
$value.file_name contains "/var/www/html/biology/demo/files/mpijobs/107/mothership/data/job107_0_0_output.tif"
After the script, "para" contains the edited path which is "/files/mpijobs/107/mothership/data/job107_0_0_output.tif" (the removal of "/var/www/html/biology/demo")
The code:
Download
provides a clickable link to "a.b.c.d.edu/bio/cluster//var/www/html/biology/demo/files/mpijobs/107/mothership/data/job107_0_0_output.tif"
and what I want to do is replace "{$value.file_name}" inside the brackets with "para" (and what it represents) so that the download link is linked to
"a.b.c.d.edu/bio/cluster//files/mpijobs/107/mothership/data/job107_0_0_output.tif"
Sorry, I misunderstood.
If the a href attribute is set like so:
Download
You can use in the javascript:
str.setAttribute("href", res);
EDIT:
Ok I got it. Sorry about this strenuous exercise. Here's what you should write:
<p id="demo">{$value.file_name}</p>
<a href="#para" id='para'>Download</a>
<script type="text/javascript">
var str = document.getElementById("demo").innerHTML;
var res = str.replace("/var/www/html/biology/demo", "");
para = document.getElementById('para');
para.href = res;
</script>
I have a html page with buttons:
<INPUT TYPE=BUTTON VALUE="b1" onclick="init1()" >
init1:
document.innerHTML = "<object type='application/x-app' id='plugin' width='0' height='0' > </object>"
When I press the button b1 it erase the page and it just blank.
What am I doing wrong?
10xs,
Nir
Use appendChild on body instead of replacing (=). Your button will not get erased.
var object = document.createElement("object");
object.innerHTML = "<object...";
document.body.appendChild(object);
You need to adres proper anchor (place) in your code (in the DOM tree).
Try this instead:
var my_anchor = document.getElementById('element_in_DOM');
my_anhor.innerHTML = "<object type='application/x-app' id='plugin' width='0' height='0' > </object>"
Of course it erases the page. When you modify the .innerHTML of the -entire document-, and replace it with something else, that's what happens.
If you want to append that tag onto the document however, that's a different story. I would suggest the following to do such:
var your_element = document.createElement('object');
your_element.type = 'application/x-app';
your_element.id = 'plugin'
your_element.width = 0;
your_element.height = 0;
document.body.appendChild(your_element);
DEMO