How to display array from local storage in html element? - javascript

Obviously, a beginner's question:
How do I get array data to display in an html element using html and javascript?
I'd like to display the user saved array data in a paragraph tag, list tag, or table tag, etc.
[http://www.mysamplecode.com/2012/04/html5-local-storage-session-tutorial.html]
Above is a link to the kindly provided example of localStorage except how to display the array on the html page rather than in the console.log.
Below is the code snip that demonstrates what I'm trying to do.
function saveArrayData() {
console.log("Saving array data to local storage.");
var myArrayObject = [];
var personObject1 = new Object();
personObject1.name = "Array1";
personObject1.age = 23;
myArrayObject.push(personObject1);
var personObject2 = new Object();
personObject2.name = "Array2";
personObject2.age = 24;
myArrayObject.push(personObject2);
var personObject3 = new Object();
personObject3.name = "Array3";
personObject3.age = 25;
myArrayObject.push(personObject3);
localStorage.setItem("persons", JSON.stringify(myArrayObject));
}
function restoreArrayData() {
console.log("Restoring array data from local storage.");
var myArrayObject = JSON.parse(localStorage.getItem("persons"));
for (var i = 0; i < myArrayObject.length; i++) {
var personObject = myArrayObject[i];
console.log("Name: " + personObject.name, "Age: " + personObject.age);
}
}
<label for="name">Name:</label>
<input type="text" data-clear-btn="true" name="name" id="name" value="">
<label for="age">Age:</label>
<input type="text" data-clear-btn="true" name="age" id="age" value="">
<br>
<br>
<input type="button" id="sArray" value="Save Array data" onclick="Javascript:saveArrayData()">
<input type="button" id="rArray" value="Restore Array data" onclick="Javascript:restoreArrayData()">
<p id="displayArrayDataHere"></p>

You should update your code like below:
function restoreArrayData() {
var myArrayObject = JSON.parse(localStorage.getItem("persons"));
$("#displayArrayDataHere").append("<table>");
myArrayObject.forEach(function(personObject) {
$("#displayArrayDataHere").append("<tr><td>"+personObject.name+"</td><td>"+personObject.age+"</td></tr>")
})
$("#displayArrayDataHere").append("</table>");
}

Related

How to clone or create a nested DOM node and change all its containing id values according to a current id?

I need to display some numbers, strings from a class named Student, but i can't figure it out how i can change the id from children element. I have to use JavaScript.
what i tried to do:
class Student{
static count = 0;
constructor(nume, prenume, data_nasterii, foaie_matricola){
this.IdClasa = ++Student.count;
//definirea atributelor
this.nume = nume;
this.prenume = prenume;
this.data_nasterii = data_nasterii;
this.foaie_matricola = foaie_matricola;
}
afiseazaVarsta(){
}
afiseazaNotele(){
}
calculeazaMedia(){
}
adaugaNota(nota_noua){
}
}
var Stud = [new Student("Name", "Name1", "2000.01.01", "0123123"),
new Student("Green", "Blue", "2022/12.12", "321321")];
function afisareStudenti(){
let i = 0; let bol = false;
for(let x=1; x<=Student.count; x++) {
console.log(document.getElementById("AfisareStudenti"+x)==null);
if(document.getElementById("AfisareStudenti"+x)==null)
{
i = x;
bol = true;
break;
} else {
bol = false;
}
}
if((i<=Student.count)&&(bol==true)){
for(i; i<=Student.count; i++) {
console.log("i="+i);
var div = document.querySelector('#AfisareStudenti1');
var divClone = div.cloneNode(true);
console.log(divClone);
divClone.id = 'AfisareStudenti'+(i);
div.after(divClone);
var NumeStud = document.getElementById("NumeStudent"+(i-1));
var PrenumeStud = document.getElementById("PrenumeStudent"+(i-1));
var dataNastStud = document.getElementById("intData"+(i-1));
var FoaiaMatStud = document.getElementById("FoaiaMatStud"+(i-1));
NumeStud.id = "NumeStudent"+(i);
PrenumeStud.id = "PrenumeStud"+(i);
dataNastStud.id = "intData"+(i);
FoaiaMatStud.id = "FoaiaMatStud"+(i);
}
}
}
and this is the html file(the div that i want to clone):
<!--AFISARE-->
<div id="AfisareStudenti1">
<h2> Afisare Student 1</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent1"><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent1"><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData1"><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud1"><br><br>
<input class="butoane" type="submit" value="Afisare"
onclick="afisareMeniuAfisStudenti()">
</form>
</div>
the class is saved in a dynamic array (could be n object of the class) so i have to make somehow to display the information dynamic. My version changes the id from all elements with the same id (every incrementation of i, the idnumber from id is incremented also). I tried to create that div with document.createElement but is impossible(at least for me) xD . I started coding in javascript 2 days ago, so please take it slow on me :(
I think i found the problem, but it doesn't solve it. (i need to put (i-1) when calling for getting the ids). (Newbie mistake)
Having commented ...
"I have the feeling that if provided with the broader picture the audience could be of much more help since the OP could be provided back with leaner/cleaner and better maintainable approaches."
... I nevertheless hereby lately provide a template-based approach which, besides supporting the OP's id based querying of student-items, is also easier to read and to maintain.
The code provided within the example-code's main function does not just implement the usage of the template-based node-creation via template literals and DOMParser.parseFromString but also prevents the default behavior of each student-form's submit-button by making use of event-delegation.
function createStudentElement(studentId) {
const markup =
`<div class="student-item" id="AfisareStudenti${ studentId }">
<h2> Afisare Student ${ studentId }</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent${ studentId }"><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent${ studentId }"><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData${ studentId }"><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud${ studentId }"><br><br>
<input
class="butoane" type="submit" value="Afisare"
onclick="afisareMeniuAfisStudenti(${ studentId })"
>
</form>
</div>`;
const doc = (new DOMParser).parseFromString(markup, 'text/html');
return doc.body.removeChild(doc.body.firstElementChild);
}
// the button click handler.
function afisareMeniuAfisStudenti(studentId) {
console.log({ studentId })
}
function main() {
const itemsRoot = document.querySelector('.student-items');
// - prevent any form-submit by making use of event-delegation.
itemsRoot.addEventListener('submit', evt => evt.preventDefault());
// - just for demonstration purpose ...
// ... create student-items from a list of student IDs.
[1, 2, 3, 4, 5].forEach(studentId =>
itemsRoot.appendChild(
createStudentElement(studentId)
)
);
}
main();
.as-console-wrapper { left: auto!important; width: 50%; min-height: 100%; }
<div class="student-items"></div>
Tom's answer above is what you want for the element id problem that you asked about.
For your code in particular, you are going to have a couple other problems:
Because the final input is type="submit", its going to reload the page by default when it is clicked. The name of the "onclick" function also needs to match the function you defined (afisareStudenti).
You have:
<input class="butoane" type="submit" value="Afisare" onclick="afisareMeniuAfisStudenti()">
Change this to:
<input class="butoane" type="submit" value="Afisare" onclick="afisareStudenti(event)">
Now, when you click that button, it will call the afisareStudenti function and pass in the "event". So if you change:
function afisareStudenti(){
let i = 0; let bol = false;
to:
function afisareStudenti(event){
event.preventDefault()
let i = 0; let bol = false;
This will correctly call your function, and prevent the "default" action of that submit button from reloading the page.
To change the id attribute of children elements, you could use Element.querySelector() on divClone.
Because if you use Document.querySelector() or Document.getElementById() you will get the first element that matches your selector (i.e.children of div#AfisareStudenti1).
let i = 2;
var div = document.querySelector('#AfisareStudenti1');
var divClone = div.cloneNode(true);
divClone.id = 'AfisareStudenti'+(i);
divClone.querySelector("h2").innerText = "Afisare Student " + i;
var NumeStud = divClone.querySelector("#NumeStudent1");
var PrenumeStud = divClone.querySelector("#PrenumeStudent1");
var dataNastStud = divClone.querySelector("#intData1");
var FoaiaMatStud = divClone.querySelector("#FoaiaMatStud1");
NumeStud.id = "NumeStudent"+(i);
PrenumeStud.id = "PrenumeStud"+(i);
dataNastStud.id = "intData"+(i);
FoaiaMatStud.id = "FoaiaMatStud"+(i);
div.after(divClone);
<div id="AfisareStudenti1">
<h2> Afisare Student 1</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent1" /><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent1" /><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData1" /><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud1" /><br><br>
<input class="butoane" type="submit" value="Afisare" onclick="afisareMeniuAfisStudenti()" />
</form>
</div>

Javascript wont add data to table in html

I was not able to get this to display the data entered into my table like I wanted. Keeps saying "Uncaught ReferenceError: createRequest is not defined
at HTMLButtonElement.onclick" however I did! or I thought I did... please help me to see what I did wrong! I tried fixing the error messages but it doesn't seem to help.
thank you
function myRequest(medium, subject, quantity) {
requestMedium = medium;
requestSubject = subject;
requestQuantity = quantity;
}
var requestButton = document.getElementById("createRequest");
if (requestButton.addEventListener) {
requestButton.addEventListener("click", Request, false);
} else if (requestButton.attachEvent) {
requestButton.attachEvent("onclick", Request);
}
function createRequest
{
var requestMedium = document.getElementById(medium).value;
var requestSubject = document.getElementById(subject).value;
var requestQuantity = document.getElementById(quantity).value;
//create new request request, store reference in myRequest
//myRequest= new request(requestMedium, requestSubject, requestQuantity);
var addRequest = new Request(requestMedium, requestSubject, requestQuantity);
//display usere's request on page
createRequestDisplay(addRequest);
}
//display gloval request object on page
function displayRequest() {
document.getElementById("requestDisplay").innerHTML = Request.requestMedium + "<br>" +
Request.requestSubject + "<br>" +
Request.requestQuantity;
}
//display any request object to new document node on page
function createDisplayRequest(request) {
// create new object div element
var fragment = document.createElement("div");
//add newObject class name to div element
var classAttrib = document.createAttribute("class");
classAttrib.value = "newObject";
//set class attibute to div fragment;
fragment.setAttributeNode(classAttrib);
//put request object info inside div
fragment.innerHTML = requestMedium + < "br" > +
requestStubject + < "br" > +
requestSubject;
document.body.appendChild(fragment);
}
<div class="main">
<h1>Order Form for comissions</h1>
<legend>Request Comission</legend>
<label for="medium">Medium</label>
<input id="medium" type="text"><br>
<label for="subject">Subjects</label>
<!-- Grader: HTML error needs fixing...missing a '>'' character -->
<!-- <input id="subject" type="subject"<br> -->
<input id="subject" type="text">
<label for="quantity">quantity</label>
<input id="quantity" type="number"><br>
<button id="requestButton" onclick="createRequest">Submit</button>
</div>
<div id="displayRequest">
</div>
Here is a fixed version
var submitRequestBtn = document.getElementById("submitRequestBtn");
submitRequestBtn.addEventListener("click", submitRequest, false);
function submitRequest() {
const medium = document.getElementById('medium').value;
const subject = document.getElementById('subject').value;
const quantity = document.getElementById('quantity').value;
const request = {medium, subject, quantity};
displayRequest(request);
}
function displayRequest(request){
document.getElementById("requestDisplay").innerHTML =
request.medium + "<br>"
+ request.subject + "<br>"
+ request.quantity
;
}
<div class="main">
<h1>Order Form for comissions</h1>
<legend>Request Comission</legend>
<label for="medium">Medium</label>
<input id="medium" type="text"><br>
<label for="subject">Subjects</label>
<input id="subject" type="text">
<label for="quantity">quantity</label>
<input id="quantity"type="number"><br>
<button id="submitRequestBtn" onclick="submitRequest()">Submit</button>
<br/>
<div id ="requestDisplay"></div>
</div>

Creating a compressing function in HTML

So i've been asked for creating a function that compress a string.
I tried to create a javascript function to do that. But it seems, it is not doing anything for the moment. I don't understand why, regardless of the input, my function is not doing anything.
function compression(input) {
var charsToEscape = "#/%&+,!()*':;<=>?";
var escaped = [];
for (var i = 0; i < input.length; i++) {
var testChar = input.substr(i, 1);
if (charsToEscape.indexOf(testChar) > -1) {
escaped.push("%" + testChar.charCodeAt(0).toString(16).toUpperCase());
} else {
escaped.push(testChar);
}
}
return escaped.join("");
}
<label for="input">Input: Uncompressed Link URI</label>
<input type="text" id="input" class="form-control" name="input" value="">
<button onclick="compression(input)" name="button">Compressed </button>
<br><br>
<label for="compression">Output: Compressed Link URI</label>
<input type="text" id="compression" class="form-control" name="compression" value="">
You can see above, the html function is where i put my input, and the output, and the javascript function that is supposed to do the compression.
But for the moment he is not doing anything.
Thank you all in advance for any advice you could provide
1st: You didn't use the value of the input element, but the element itself. So input hase to be replaced with input.value
2nd: You returned a value, but didn't do anything with it.. So you could create a new function that will get the value and put it in the second input
3rd: Your ids' names are too generic. I changed them to be more specific and telling names which will not interfere with other elements in the same page.
function compression(input) {
var charsToEscape = "#/%&+,!()*':;<=>?";
var escaped = [];
for (var i = 0; i < input.value.length; i++) {
var testChar = input.value.substr(i, 1);
if (charsToEscape.indexOf(testChar) > -1) {
escaped.push("%" + testChar.charCodeAt(0).toString(16).toUpperCase());
} else {
escaped.push(testChar);
}
}
return escaped.join("");
}
function insertCompressed(output, value) {
output.value = value
}
<label for="input">Input: Uncompressed Link URI</label>
<input type="text" id="compressionInput" class="form-control" name="input" value="">
<button onclick="insertCompressed(compressionOutput, compression(compressionInput))" name="button">Compressed </button>
<br><br>
<label for="compression">Output: Compressed Link URI</label>
<input type="text" id="compressionOutput" class="form-control" name="compression" value="">
I've created an onCompress function which takes html element as input. The function gets the desired input element, compression and assigns the compressed value to it.
function onCompress(input) {
document.getElementById('compression').value = compression(input.value);
}
function compression(text) {
var charsToEscape = "#/%&+,!()*':;<=>?";
var escaped = [];
for (var i = 0; i < text.length; i++) {
var testChar = text.substr(i, 1);
if (charsToEscape.indexOf(testChar) > -1) {
escaped.push("%" + testChar.charCodeAt(0).toString(16).toUpperCase());
} else {
escaped.push(testChar);
}
}
return escaped.join("");
}
<label for="input">Input: Uncompressed Link URI</label>
<input type="text" id="input" class="form-control" name="input" value="">
<button onclick="onCompress(input)" name="button">Compressed </button>
<br><br>
<label for="compression">Output: Compressed Link URI</label>
<input type="text" id="compression" class="form-control" name="compression" value="">

JS: Push to array and update select without getting duplicates

I am populating a SELECT with an array. The array contains strings with employee-names.
I want to be able to add a new employee name in the array and then update the SELECT. I've made this, but I keep getting duplicates as I call the function. I kind of understand why, but I haven't quite figured out yet how to make this code better so that I only add the one employee name that is written in the text input.
I don't want to have a function that removes all duplicates, as I think it should be possible to have several employees with the name "John".
My HTML:
<section id="sidebar">
<form onSubmit="return false">
<label for="Name">Name:</label>
<input id="nameInput" type="text" value="Your name here..." name="name" />
<input type="submit" value="Add to list" name="Add" onClick="addToArray();"><br>
<label for="Default">List over employees:</label>
<select id="employeeSelect">
</select>
</form>
</section>
My JS:
var employeeList = ['Sarah', 'Louse', 'Dan', 'John', 'Peter'];
function listEmployees(){
var select = document.getElementById('employeeSelect');
for (var i = 0; i < employeeList.length; i++)
{
var option = employeeList[i];
var newOption = document.createElement("option");
newOption.textContent = option;
newOption.value = option;
select.appendChild(newOption);
}
}
listEmployees();
function addToArray(){
var txtbox = document.getElementById('nameInput');
var value = txtbox.value;
employeeList.push(value);
listEmployees();
}
You're calling listEmployees() (which adds, and re-adds, everything in your list) each time a new name is added.
I'd move the add-a-new-option code out to its own function. Call it for each name in the original list, then call it again when a new name is added.
var employeeList = ['Sarah', 'Louse', 'Dan', 'John', 'Peter'];
function addEmployee(name) {
var select = document.getElementById('employeeSelect');
var newOption = document.createElement("option");
newOption.textContent = name;
newOption.value = name;
select.appendChild(newOption);
}
function listEmployees() {
for (var i = 0; i < employeeList.length; i++) {
addEmployee(employeeList[i])
}
}
listEmployees();
function addToArray() {
var txtbox = document.getElementById('nameInput');
var value = txtbox.value;
employeeList.push(value); // update the list
addEmployee(value); // update the select
}
<section id="sidebar">
<form onSubmit="return false">
<label for="Name">Name:</label>
<input id="nameInput" type="text" placeholder="Your name here..." name="name" />
<input type="submit" value="Add to list" name="Add" onClick="addToArray();">
<br>
<label for="Default">List over employees:</label>
<select id="employeeSelect">
</select>
</form>
</section>

Getting value of <p> without the use of innerHTML

first of all I'm sorry if this is a long code segment however, I'm trying to make a modal window which writes the thing you wrote in my user form and asks you to confirm it. I am currently in a class to learn Javascript and I'm not allowed to use innerHTML and I must write the "Firstname:" etc dynamically (the text for firstname) and am not allowed to just write it inside the popup window. I've gotten most stuff to work but the "Firstname:" "Lastname" etc comes up as "undefined" or (as you can see the thing I tried with just the first name in this case) comes up as "null".
Hopefully someone can shed some light on this subject for me, this is the HTML:
<form action="http://voyager.lnu.se/tekinet/kurser/dtt/wp_webbteknik/process_form.php" method="POST" id="userform" target="_blank">
<p id="formQuestion1">Förnamn</p>
<div id="error1"></div>
<input type="text" name="firstName" id="test"/>
<p id="formQuestion2">Efternamn</p>
<div id="error2"></div>
<input type="text" name="lastName" />
<p id="formQuestion3">Postnummer</p>
<div id="error3"></div>
<input type="text" name="postCode" id="codeText"/>
<p id="formQuestion4">E-post</p>
<div id="error4"></div>
<input type="text" name="eMail" />
<br />
<br />
<label id="model" class="formQuestion" for="priceModel">Prismodell</label>
<br />
<select name="Type" id="priceModel">
<option value="Låg" selected>Låg</option>
<option value="Medel">Medel</option>
<option value="Hög">Hög</option>
</select>
<br />
<br />
<br />
<input id="sendButton" type="submit" value="Genomför Köp" />
</form>
And here is the segment for the modal window (Javascript)
function popup(backgroundDiv) {
var popForm = document.getElementById("userform");
var myDiv = document.createElement("div");
myDiv.className = "popupWindow";
var priceModel = document.getElementById("priceModel");
// Knappar
var newButton = document.createElement("button");
var newerButton = document.createElement("button");
newButton.setAttribute("value", "Skicka");
newButton.innerHTML = "Skicka"; // Here I actually use innerHTML because I don't know
newerButton.innerHTML = "Stäng"; // any other way to set the text inside the button
newButton.className = "popupButton";
newerButton.className = "popupButton";
newButton.setAttribute("id", "Skicka");
newerButton.setAttribute("id", "Avbryt");
myDiv.appendChild(newButton);
myDiv.appendChild(newerButton);
// Information
var h1 = document.createElement("h1");
h1.setAttribute("id", "popuph1");
var h1Text = document.createTextNode("Vänligen kontrollera dina uppgifter");
var text = document.getElementById("formQuestion1");
var writeFname = text.nodeValue + popForm.elements.firstName.value;
var writeLname = document.getElementById("formQuestion2").value + popForm.elements.lastName.value;
var writeCode = document.getElementById("formQuestion3").value + popForm.elements.postCode.value;
var writeMail = document.getElementById("formQuestion4").value + popForm.elements.eMail.value;
var writePlan = document.getElementById("model").value + priceModel.value;
var p1 = document.createTextNode(writeFname);
var p2 = document.createTextNode(writeLname);
var p3 = document.createTextNode(writeCode);
var p4 = document.createTextNode(writeMail);
var p5 = document.createTextNode(writePlan);
h1.appendChild(h1Text);
myDiv.appendChild(h1);
myDiv.appendChild(p1);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p2);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p3);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p4);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p5);
document.body.appendChild(myDiv);
newButton.onclick = function () {
document.body.removeChild(myDiv);
document.body.removeChild(backgroundDiv);
return true;
};
If you don't want to use innerHTML then you can use those options, suppose you want value from this node <p id="formQuestion1">Förnamn</p>
Then your code would be
var dom = document.getElementById('formQuestion1');
1) var res = dom.innerText;
OR
2) var res = dom.textContent;
OR
3) var res = dom.firstChild.nodeValue;

Categories