I want to use the to be able to type data into a page, press a button to save the data, then be able to close and re-open the page with the saved data.
I have been able to do this with the code below with 1 text area, but if I use multiples, it only displays the last entered data.
Here's my code:
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
function saveEdits() {
//get the editable element
var editElem = document.getElementById("CPU")
var editElem = document.getElementById("RAM")
var editElem = document.getElementById("HDD")
//get the edited element content
var userVersion = editElem.innerHTML;
//save the content to local storage
localStorage.userEdits = userVersion;
//write a confirmation to the user
document.getElementById("update").innerHTML="Edits saved!";
}
function checkEdits() {
//find out if the user has previously saved edits
if(localStorage.userEdits!=null)
document.getElementById("CPU").innerHTML = localStorage.userEdits
document.getElementById("RAM").innerHTML = localStorage.userEdits
document.getElementById("HDD").innerHTML = localStorage.userEdits
}
</script>
</head>
<body onload="checkEdits()">
<label>Processor : </label>
<div id="CPU" contenteditable="true"></div><br><br><br>
<label>RAM : </label>
<div id="RAM" contenteditable="true"></div><br><br><br>
<label>Hard Drive : </label>
<div id="HDD" contenteditable="true"></div><br><br><br>
<input type="button" value="SAVE" onclick="saveEdits()"/>
<div id="update"></div>
</body>
</html>
You need to have 3 different variables for each of the 3 inputs, see fiddle: https://jsfiddle.net/xtat0oa6/5/
javascript
function saveEdits() {
//get the editable element
var editElem1 = document.getElementById("CPU")
var editElem2 = document.getElementById("RAM")
var editElem3 = document.getElementById("HDD")
//get the edited element content
var userVersion1 = editElem1.innerHTML;
var userVersion2 = editElem2.innerHTML;
var userVersion3 = editElem3.innerHTML;
//save the content to local storage
localStorage.userEdits1 = userVersion1;
localStorage.userEdits2 = userVersion2;
localStorage.userEdits3 = userVersion3;
//write a confirmation to the user
document.getElementById("update").innerHTML = "Edits saved!";
}
function checkEdits() {
//find out if the user has previously saved edits
if (localStorage.userEdits1 != null || localStorage.userEdits2 != null || localStorage.userEdits3 != null){
document.getElementById("CPU").innerHTML = localStorage.userEdits1
document.getElementById("RAM").innerHTML = localStorage.userEdits2
document.getElementById("HDD").innerHTML = localStorage.userEdits3}
}
Related
I'm trying to add a new item on an array that displays in a container on HTML. It's supposed to get an image file and an url from input, check the selected option and push each one to its specified array
Here is the relevant html:
<input type="file" name="comic-cover" id="comic-cover" required />
<input type="url" name="comic-url" id="comic-url" placeholder="url" required />
<select name="publisher-list" id="publisher">
<option value="publisher" disabled>Publisher</option>
<option value="dc">DC Comics</option>
<option value="marvel">Marvel</option>
</select>
<button type="submit" class="btn-submit">Add</button>
<h2 class="comic-publisher">DC Comics</h2>
<div class="dc" id="block-dc">
</div>
<h2 class="comic-publisher">Marvel</h2>
<div class="marvel" id="block-marvel">
</div>
and the js:
var comicCovers = ["imgs/Dark Knights of Steel-000.jpg", "imgs/Hawkeye-000.jpg"]
var trailers = ["https://www.youtube.com/watch?v=WspmgrmEgn4", "https://www.youtube.com/watch?v=ssj0P0uY08U"]
var publishers = [0, 1];
var i = 0;
var blockDC = document.querySelector("#block-dc");
var blockMarvel = document.querySelector("#block-marvel");
render()
var publisher = document.querySelector("select").value;
document.querySelector("select") = function renderPublisher() {
publisher = document.querySelector("select").value;
return publisher;
}
// add new comics to the list //
document.querySelector(".btn-submit") = function addOnList() {
var newCover = document.querySelector("#comic-cover");
var newTrailer = document.querySelector("#comic-url");
if (newCover.endsWith(".jpg") & newTrailer.startsWith("https://")) {
if (publisher == "dc") {
publisher.push(0);
} else {
publisher.push(1)
}
comicCovers.push(newCover.value);
trailers.push(newTrailer.value);
newCover.value = "";
newTrailer.value = "";
render()
}
}
function render() {
for (i; i < comicCovers.length; i++) {
// creates the comic covers using js var //
var comicCover = document.createElement("img");
comicCover.setAttribute("src", `${comicCovers[i]}`);
// creates trailer button //
var trailerButton = document.createElement("button");
// //
var container = document.createElement("div");
container.setAttribute("class", "container");
container.appendChild(trailerButton);
container.appendChild(comicCover);
blockDC.appendChild(container);
trailerButton.appendChild(document.createTextNode("Trailer"));
trailerButton.setAttribute("class", "trailer-button");
trailerButton.setAttribute("onclick", `openTrailer("${trailers[i]}")`);
if (publishers[i] == 0) {
blockDC.appendChild(container);
} else {
blockMarvel.appendChild(container);
}
}
}
I tried to use if (newCover != "" & newTrailer != "") and even changed the input type from file to url. What am I doing wrong?
You're tring to push values inside the variable called publisher which is just a string and not an array.
var publisher = document.querySelector("select").value;
publisher.push(0);
You're assigning a function to an html element by writing:
document.querySelector("select") = function renderPublisher() {
publisher = document.querySelector("select").value;
return publisher;
}
which is not correct.
Also The variables newCover and newTrailer are not strings.
var newCover = document.querySelector("#comic-cover");
var newTrailer = document.querySelector("#comic-url");
so you can't use the methods startsWith and endsWith for them, you have to access the elements' value instead. In order to get the name of the selected file you need to use the input tag's files attribute which returns an array of the selected files, we want the first file so we'll get the first item's name attribute.
var newCover = document.querySelector("#comic-cover").value;
var newTrailer = document.querySelector("#comic-url")?.files[0]?.name;
Overall first you need to grab the values provided inside the inputs, then push them inside the array related to the selected block(Marvel or DC), then you simply need to create the img, video and button tags and append them as a child to the selected block.
Url and file type validation should be handled also on both server and client side and it's gotta be much more than just checking if the fileName ends with ".jpg" or the url starts with "https://".
You need to store the uploaded image and video somewhere on the server. In order to do so, you'll have to attach an eventListener to the input tags so that whenever a file is selected, you'll send an upload request to the server, there you'll check if the file is valid and if so, you'll store the file somewhere on the server, then you'll pass the url of the uploaded photo/video as src to the img/video tags.
const publishers = {
dc: {
comicCovers: [],
trailers: []
},
marvel: {
comicCovers: [],
trailers: []
}
}
const blockDC = document.querySelector("#block-dc");
const blockMarvel = document.querySelector("#block-marvel");
const blocksDivs = {
dc: blockDC,
marvel: blockMarvel
};
const addButton = document.querySelector(".btn-submit");
// add new comics to the list //
addButton.addEventListener("click", () => {
const publisher = document.querySelector("#publisher").value;
const newCoverFileName = document.querySelector("#comic-cover")?.files[0]?.name;
const newTrailerUrl = document.querySelector("#comic-url").value;
if (newCoverFileName?.endsWith(".jpg") && newTrailerUrl?.startsWith("https://")) {
publishers[publisher].comicCovers.push(newCoverFileName);
publishers[publisher].trailers.push(newTrailerUrl);
var container = document.createElement("div");
var coverImg = document.createElement("img");
var playTrailerButton = document.createElement("button");
playTrailerButton.innerHTML = "play trailer"
coverImg.src = "http://yourserveraddress/imgs/" + newCoverFileName;
//test photo
coverImg.src = "https://picsum.photos/200/300"
container.appendChild(coverImg);
container.appendChild(playTrailerButton);
blocksDivs[publisher].appendChild(container);
playTrailerButton.setAttribute("class", "trailer-button");
playTrailerButton.addEventListener("click", () => {
var videoExists = document.getElementById(publishers[publisher].trailers.length)
if (!videoExists) {
var video = document.createElement('video');
video.setAttribute("id", publishers[publisher].trailers.length)
video.style.backgroundColor = "aliceblue"
video.setAttribute("src", newTrailerUrl);
video.setAttribute("width", "200")
video.setAttribute("height", "200")
container.appendChild(video);
playTrailerButton.innerHTML = "close Trailer"
} else {
container.removeChild(videoExists)
playTrailerButton.innerHTML = "play Trailer"
}
})
}
})
<input type="file" name="comic-cover" id="comic-cover" required />
<input type="url" name="comic-url" id="comic-url" placeholder="url" required />
<select name="publisher-list" id="publisher">
<option value="publisher" disabled>Publisher</option>
<option value="dc">DC Comics</option>
<option value="marvel">Marvel</option>
</select>
<button type="submit" class="btn-submit">Add</button>
<h2 class="comic-publisher">DC Comics</h2>
<div class="dc" id="block-dc">
</div>
<h2 class="comic-publisher">Marvel</h2>
<div class="marvel" id="block-marvel">
</div>
I am using TypeForm and need to autofill utm fields from javascript, everything works except I cant get the html created from the script to show on the page. I am embedding the below code in a html/js module in a clickfunnels page. Any help is very much appreciated.
<div id="typeform"></div>
<script>
//<div id="typeform"></div> <div id="row--27712"></div>
window.onload = function(){
var source = "utm_source=1";
var medium = "utm_medium=2";
var campaign = "utm_campaign=3";
var content = "utm_content=4";
var keyword = "utm_term=5"
var HTMLA = '<div data-tf-widget="mYH43Dz4" data-tf-iframe-props="title=TFS - ANALYTICSDEV V1.1" data-tf-medium="snippet" data-tf-hidden=';
var HTMLquote = '"';
var HTMLcomma = ',';
var HTMLB = '" style="width:100%;height:600px;"></div><script src="//embed.typeform.com/next/embed.js">';
var HTMLC = '</'
var HTMLD = 'script>'
var form = HTMLA.concat(HTMLquote).concat(source).concat(HTMLcomma).concat(medium).concat(HTMLcomma).concat(campaign).concat(HTMLcomma).concat(content).concat(HTMLcomma).concat(keyword).concat(HTMLB);
var form2 = form.replaceAll("undefined","");
document.getEIementById('typeform').innerHTML = form2;
};
</script>
You can pass custom values to hidden fields like this:
<div id="typeform"></div>
<link rel="stylesheet" href="//embed.typeform.com/next/css/widget.css" />
<script src="//embed.typeform.com/next/embed.js"></script>
<script>
var source = '1';
var medium = '2';
var campaign = '3';
var content = '4';
var keyword = '5';
window.tf.createWidget('mYH43Dz4', {
container: document.getElementById('typeform'),
hidden: {
utm_source: source,
utm_medium: medium,
utm_campaign: campaign,
utm_content: content,
utm_term: keyword
}
});
</script>
In case you already have those values in your host page URL, you could use transitive search params feature:
<div
data-tf-widget="mYH43Dz4"
data-tf-transitive-search-params="utm_source,utm_medium,utm_campaign,utm_content,utm_term"
></div>
<script src="//embed.typeform.com/next/embed.js"></script>
Your code does not work because you are adding script tag via innerHTML. This script tag will not execute for security purposes:
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations
https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0
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/
I'm back and i tried it but is doesn't work anyone that can help??? i have already put in the save mechanism.
(i had to add extra text so this has nothing to do with the script itself)
this is the code that i used to test the save mechanism.
<!DOCTYPE html>
<html>
<body>
<button onclick="point();">points</button>
<button onclick="upgrade()">upgrade</button>
<script language="javascript">
var pointcount = 0;
var totalcliks = 0;
var upgrades = 0;
function point() {
pointcount++;
totalcliks++;
}
function upgrade() {
upgrades++;
pointcount--;
}
function load() {
var testerload = document.getElementById("savecodetextbox").value;
document.getElementById("saveshow").innerHTML = testerload;
}
var pointcounterclock = setInterval(function() {pointcounter()},100);
function pointcounter(){
document.getElementById("points-screen").innerHTML = pointcount+" points";
document.getElementById("clicktotal").innerHTML = totalcliks+" totalcliks";
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
}
let savecode = "1a1a1"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[1];
updates = codes[2];
pointcount = codes[3];
}
</script>
<h3 id="points-screen"></h3>
<h3 id="clicktotal"></h3>
<h3 id="savecode"></h3>
<textarea name="text_area" id="savecodetextbox" rows="4" cols="40"></textarea> <button onclick="load()">load</button>
<h3 id="saveshow"></h3>
</body>
</html>
I'm going to alter your save code so I don't have to confuse you with regular expressions or funky splits:
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
Which means your save code could look something like: 4a6a9
Do a simple split:
let savecode = "4a5a6"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[0];
upgrades = codes[1];
pointcount = codes[2];
}
As for implementing the variables, reload the game after
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.