create the variable link as a hyperlink javascript - javascript

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/

Related

Covert html in javascript to HTML tags

I'm working on the tooltips and from the backend I'll get data in with html tags. I need to show in the tooltip with its corresponding data in its respective tags. For example, I'll get hello user click here from the backend. I've to show as hello user in h1 format and click here should be a anchor. I tried with both functions and replace its not working.
With function:
<h1 id="data">
</h1>
function convertToPlain(html){
var tempDivElement = document.createElement("div");
tempDivElement.innerHTML = html;
return tempDivElement.textContent || tempDivElement.innerText || "";
}
var htmlString= "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute<a> click here<a></p></div>";
let dataVal = convertToPlain(htmlString)
document.getElementById("demo").innerHTML = dataVal;
With replace:
https://codesandbox.io/s/serene-fast-u8fie?file=/App.svelte
I made below snippet by copy-paste your code and just update return statement inside convertToPlain function, also I added href attribute to <a> in the htmlString content.
function convertToPlain(html) {
var tempDivElement = document.createElement("div");
tempDivElement.innerHTML = html;
return tempDivElement.innerHTML;
}
var htmlString = "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute<a href='#'> click here<a></p></div>";
let dataVal = convertToPlain(htmlString)
document.getElementById("demo").innerHTML = dataVal;
<h1 id="demo"></h1>

How to link an appended title?

I currently have an editor that allows users to enter input and save their input under a specific title. I have a button which allows them to do so, as well as adding the name of their title to a box (just a div with white background) using append child.
Was wondering how I could link these titles, such that when they click on one title, the text input assigned to said title shows up inside my editor?
Javascript:
<!-- Function to save the user's input inside editor1 -->
function saveEdits() {
var editElem = document.getElementById("editor1");
var userVersion = editElem.innerHTML;
localStorage.userEdits = userVersion;
//Get the title from the user
var title = prompt("What would you like your title to be?");
localStorage.setItem(title, editElem.innerHTML);
//Asigning the titles input by the user to the key "titles"
titles = localStorage.getItem("titles");
if (titles == null){
titles = [];
}
else {
titles = JSON.parse(titles);
}
var obj;
obj = {"titles": title};
titles.push(obj);
localStorage.setItem("titles",JSON.stringify(titles));
//Save the editor contents to local storage based on title
document.getElementById("update").innerHTML = "Edits saved!";
var theDiv = document.getElementById("Contentable");
var content = document.createTextNode(title);
theDiv.appendChild(content);
var br = document.createElement("br");
theDiv.appendChild(br);
}
<!-- Function to check if the user has any saved input -->
function checkEdits() {
if(localStorage.userEdits != null)
document.getElementById("editor1").innerHTML = localStorage.userEdits;
}
function loadEdits(title) {
//load useredit for title from local storage
var userEdits = localStorage.getItem(title);
var editElem = document.getElementById("editor1");
editElem.innerHTML = userEdits;
}
HTML (Editor):
<!-- Editor 1 -->
<div id="editor1" contenteditable="true" style="margin-left:30em">
</div>
<input id="savechanges" type="button" value="Save Changes" onclick="saveEdits()"/>
<div id="update">Click to save your changes made</div>
You could attach an onclick-event to the markup. Like this.
<div class="container>
<h2 class="title" onclick="edit(this)">
EDITABLE CONTENT BELOW
</h2>
<div class="editable" onclick="edit(this)">
</div>
The js
var activeParent;
function edit( element ){
var title = element.parentNode.children[ 0 ].innerHTML;
var content = element.parentNode.children[ 1 ].innerHTML;
//do stuff with the markup
activeParent = element.parentNode;
}
That is how you can get the content and temporarily store the active parent as a reference. So when you save it is activeParent.children[ 1 ].innerHTML = editedContent.
EDIT: Since all of these are relative references you can use as many as you want. Just be careful when using the activeParent. It assumes you only edit one area at a time.

Display a link inside an if-condition using javascript

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 );

Append text input in the the text box to the url and open the url link

I have the following code:
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "www.google.com/search/" + userInput;
lnk.innerHTML = lnk.href;
}
</script>
Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' value=' ' />
<input type='button' onclick='changeText2()' value='Change Link'/>
So, this basically does the following:
User enters a word in the text box, and that word is appended at the end of the link given (www.google.com/search/). And the link is displayed above on the page.
But instead of displaying the link on the page, I want it to open that page when the button is clicked. How can I do that?
See this fiddle
Try window.location to redirect to the page on click.
That is, in your code try like
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "www.google.com/search/" + userInput;
window.location = "www.google.com/search/" + userInput;
}
</script>
You can change the current url by changing window.location
This would make your function look as follows:
function changeText2(){
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "www.google.com/search/" + userInput;
lnk.innerHTML = lnk.href;
window.location = lnk.href;
}
As pointed by others, you can use the location object in two ways
Replacing it
window.location.replace("http://url.to")
or setting the href value
window.location.href = "http://url.to"
You also need to encode the text input to make it url safe
window.location.href = "http://url.to/search?q="+encodeURIComponent("Query value")
Also, it's important to include the protocol (http) if you are linking to an external domain.

Replacing DIV content based on variable sent from another HTML file

I'm trying to get this JavaScript working:
I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.
<!-- ORIGINAL DIV -->
<div id="Email">
</div>
<!-- DIV replacement function -->
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';
ReplaceContentInContainer('Email1',content);
}
</script>
<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';
ReplaceContentInContainer('Email2',content);
}
</script>
Any ideas what I've done wrong that is causing it not to work?
Rather than inserting the element as text into innerHTML create a DOM element, and append it manually like so:
var obj = document.createElement("div");
obj.innerText = "Email 2 content";
obj.className = "test"
document.getElementById("email").appendChild(obj);
See this working here: http://jsfiddle.net/BE8Xa/1/
EDIT
Interesting reading to help you decide if you want to use innerHTML or appendChild:
"innerHTML += ..." vs "appendChild(txtNode)"
The ReplaceContentInContainer calls specify ID's which are not present, the only ID is Email and also, how are the two scripts called, if they are in the same apge like in the example the second (with a corrected ID) would always overwrite the first and also you declare the content variable twice which is not permitted, multiple script blocks in a page share the same global namespace so any global variables has to be named uniquely.
David's on the money as to why your DOM script isn't working: there's only an 'Email' id out there, but you're referencing 'Email1' and 'Email2'.
As for grabbing the content parameter from the query string:
var content = (location.search.split(/&*content=/)[1] || '').split(/&/)[0];
I noticed you are putting a closing "}" after you call "ReplaceContentInContainer". I don't know if that is your complete problem but it would definitely cause the javascript not to parse correctly. Remove the closing "}".
With the closing "}", you are closing a block of code you never opened.
First of all, parse the query string data to find the desired content to show. To achieve this, add this function to your page:
<script type="text/javascript">
function ParseQueryString() {
var result = new Array();
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
</script>
Second step, have all possible DIV elements in the page, initially hidden using display: none; CSS, like this:
<div id="Email1" style="display: none;">Email 1 Content</div>
<div id="Email2" style="display: none;">Email 2 Content</div>
...
Third and final step, in the page load (after all DIV elements are loaded including the placeholder) read the query string, and if content is given, put the contents of the desired DIV into the "main" div.. here is the required code:
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var contentId = QS["content"];
if (contentId) {
var source = document.getElementById(contentId);
if (source) {
var target = document.getElementById("Email");
target.innerHTML = source.innerHTML;
}
}
}
How about this? Hacky but works...
<!-- ORIGINAL DIV -->
<div id="Email"></div>
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
var txt = document.createTextNode(content);
container.appendChild(txt);
}
window.onload = function() {
var args = document.location.search.substr(1, document.location.search.length).split('&');
var key_value = args[0].split('=');
ReplaceContentInContainer('Email', key_value[1]);
}
</script>

Categories