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;
Related
HTML:
<body>
<h1>Grocery List</h1>
<form action="/nowhere">
<label for="item">Enter A Product</label>
<input type="text" id="product" name="product" />
<label for="item">Enter A Quantity</label>
<input type="number" id="qty" name="qty" />
<button>Submit</button>
</form>
<ul id="list"></ul>
</body>
Java Script:
const frm = document.querySelector("form");
const prdct = document.querySelector("#product");
const qty = document.querySelector("#qty");
const mylst = document.querySelector("#list");
frm.addEventListener("submit", (e) => {
e.preventDefault();
const myele = document.createElement("li");
myele.textContent = qty.value;
myele.textContent += ` ${prdct.value}`;
mylst.appendChild(myele);
qty.value = "";
prdct.value = "";
});
As can be seen, VS code isn't suggesting '.value' attribute with other suggestions. What can be the reason?
Document.querySelector() returns a Element, so the editor cannot know that it has a value.
If you would create the element by javascript, then the editor DOES know...
let input = document.createElement("input")
let test = input.value // now you can get autocomplete
Another way is to use typescript :
let input:HTMLInputElement = document.querySelector("myinput")!
let test = input.value // now you can get autocomplete
I wanted to find out whether it was possible to use a loop to simplify all this rather than hard-coding the entire structure. For the second part of my Javascript where I tried to store the user inputs into localStorage using a for loop, I'm getting an error where it says
CreateEvent.js:72 Uncaught TypeError: name.push is not a function at createReplace (CreateEvent.js:72) at HTMLButtonElement.onclick (CreateEvent.html:130)
HTML:
<span class="border1">
<input class="forms" type="text" id="title" placeholder="Enter Title!">
<p id="title1"></p>
<input class="forms" type="text" id="brief" placeholder="Enter brief description!">
<p id="brief1"></p>
</span>
<div class="Hovertrees">
<p>Hover over me!</p>
<span class="Hovertrees2">
<input class="hover" type="text" id="hover" placeholder="Enter some fun facts!">
<p id="hover1"></p>
</span>
</div>
<div id="what">
<input class="forms" type="text" id="whattitle" placeholder="What is this event?">
<h2 id="whattitle1"></h2>
<input class="forms" type="text" id="whatdesc" placeholder="Enter brief description!">
<p id="whatdesc1"></p>
</div>
<div id="why">
<input class="forms" type="text" id="whytitle" placeholder="Why is this event important?">
<h2 id="whytitle1"></h2>
<input class="forms" type="text" id="whydesc" placeholder="Description of this event">
<p id="whydesc1"></p>
</div>
<div id="fun">
<input class="forms" type="text" id="funtitle" placeholder="Anything interesting you can add!">
<h3 id="funtitle1"></h3>
<input class="forms" type="text" id="fundesc" placeholder="Description of the interesting info!">
<p id="fundesc1"></p>
</div>
Javascript:
var title;
var brief;
var hover;
var whatTitle;
var whatDesc;
var whyTitle;
var whyDesc;
var funTitle;
var funDesc;
function createReplace() {
title = document.getElementById('title').value;
document.getElementById('title1').innerHTML = title;
document.getElementById('title').className = 'hidden';
document.getElementById('news').innerHTML = title;
brief = document.getElementById('brief').value;
document.getElementById('brief1').innerHTML = brief;
document.getElementById('brief').className = 'hidden';
hover = document.getElementById('hover').value;
document.getElementById('hover1').innerHTML = hover;
document.getElementById('hover').className = 'hidden';
whatTitle = document.getElementById('whattitle').value;
document.getElementById('whattitle1').innerHTML = whatTitle;
document.getElementById('whattitle').className = 'hidden';
whatDesc = document.getElementById('whatdesc').value;
document.getElementById('whatdesc1').innerHTML = whatDesc;
document.getElementById('whatdesc').className = 'hidden';
whyTitle = document.getElementById('whytitle').value;
document.getElementById('whytitle1').innerHTML = whyTitle;
document.getElementById('whytitle').className = 'hidden';
whyDesc = document.getElementById('whydesc').value;
document.getElementById('whydesc1').innerHTML = whyDesc;
document.getElementById('whydesc').className = 'hidden';
funTitle = document.getElementById('funtitle').value;
document.getElementById('funtitle1').innerHTML = funTitle;
document.getElementById('funtitle').className = 'hidden';
funDesc = document.getElementById('fundesc').value;
document.getElementById('fundesc1').innerHTML = funDesc;
document.getElementById('fundesc').className = 'hidden';
document.getElementById("create").className = "hidden";
var varNames = [
'titles',
'brief',
'hover',
'whatTitle',
'whatDesc',
'whyTitle',
'funtitle',
'fundesc'
]
for (var name in varNames) {
var value = window[name]
var obj = {name : value};
if(localStorage.getItem(name) != null) {
var tmp = JSON.parse(localStorage.getItem(name));
for(var i = 0;i<tmp.length;i++) {
name.push(tmp[i]);
}
}
name.push(obj);
localStorage.setItem(name, JSON.stringify(value));
}
}
For the first part, simplifying is not possible since you have different properties for each elements.
For the second part, you are getting error because push is a method for array object.But name is an string object declared in for loop
for (var name in varNames) {
var value = window[name]
var obj = {name : value};
if(localStorage.getItem(name) != null) {
var tmp = JSON.parse(localStorage.getItem(name));
for(var i = 0;i<tmp.length;i++) {
name.push(tmp[i]);
}
}
name.push(obj);
localStorage.setItem(name, JSON.stringify(value));
}
}
You can set item in loop
localStorage.setItem(1,'name1');
localStorage.setItem(2,'name2');
localStorage.setItem(3,'name2');
1 2 and 3 would be key that you want to set and then get according to these keys.
localStorage.key(index)
By passing index in key method it will return you the value of that key.
I am creating a simple equation solver that involves division. I have two text boxes, One for "Mass" and one for "Element". I want to create a variable "H" and set it equal to 1, that way when the user types in "2" in the mass box and "H" in the element box, the output will say "1".
Here is my HTML
<div id="GramsToMolesContainer"><div id="GramMolesText">
<font size=3>Grams To Moles</font></div>
<form>
Grams : <input type="text" id="GramsChoice" /><br>
Element : <input type="text" id="ElementChoice" /><br>
<input type="button" onClick="GramstoMoles()" Value="Convert" />
</form>
<p>Molar Mass : <br>
<span id = "resultMolarMass"></span>
</p>
</div>
Here is my Javascript:
function GramstoMoles()
{
var H = 1;
GramsState = document.getElementById("GramsChoice").value;
ElementState =
document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML
= GramsState / ElementState;
}
you will need to create a dictionary.
this is how your function should look. every time that you want to add an element - create a new key-value pair.
function GramstoMoles()
{
var elements = {h:1, he:2};
GramsState = document.getElementById("GramsChoice").value;
ElementState =
document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML
= parseInt(GramsState) / elements[ElementState];
}
Check this working snippet of your code!
If you wan to set H as an inital value of some box, do
var ElementState = document.getElementById("ElementChoice").value = H; before you call the function.
function GramstoMoles (){
var H = 1;
var GramsState = document.getElementById("GramsChoice").value;
var ElementState = document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML = GramsState / ElementState;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="GramsToMolesContainer"><div id="GramMolesText">
<font size=3>Grams To Moles</font></div>
<form>
Grams : <input type="text" id="GramsChoice" /><br>
Element : <input type="text" id="ElementChoice" /><br>
<input type="button" onClick="GramstoMoles()" Value="Convert" />
</form>
<p>Molar Mass : <br>
<span id = "resultMolarMass"></span>
</p>
</div>
When you get the var element and var grams ,
var elements = ['H','He','Li','Be',...];
var atomicmasses = [1,4,6,9,.....];
var molarmass = molarmasses[elements.indexOf(element)];
var mole = grams/molarmass;
I have a list of buses that a user can choose to track. The html looks like this:
<div class="bus-container">
<div class="bus-heading">
<h1>My Buses</h1>
<svg width="15px" height="15px" class="add-bus"><use xlink:href="#plus"></use></svg>
</div>
<form class="hidden">
<select name="company">
<option value="greyhound">Greyhound</option>
<option value="zippy">Zippy</option>
<option value="carta">Carta</option>
</select>
<input type="text" name="number" placeholder="Enter Bus Number" />
<input type="text" name="route" placeholder="Enter the route" />
<input type="submit" value="Submit">
</form>
<div class="bus active">
<img src="img/greyhound.png" width="100" height="40" />
<p class="bus-number">12345043</p>
<p class="route">Jefferson</p>
</div>
<div class="bus active">
<img src="img/zippy.png" width="100" height="40" />
<p class="bus-number">12345043</p>
<p class="route">Jefferson</p>
</div>
<div class="bus active">
<img src="img/carta.png" width="100" height="4" />
<p class="bus-number">12345043</p>
<p class="route">Jefferson</p>
</div>
</div>
I am wondering what is the best way to use Javascript to create a new instance of the .bus div when the user inputs their info and clicks submit. I know I need to call on onsubmit function on the form and prevent the default click on the submit button itself. But I am pretty clueless as to how to append the new .bus div based on the user's input.
Try using a re-usable function called within onsubmit handler for form element, passing select value, number and route as parameters
window.onload = function() {
function addBus(company, number, route) {
var buses = document.querySelectorAll(".bus");
var curr = document.createElement("div");
curr.setAttribute("class", "bus active");
var img = new Image();
img.src = "img/" + company + ".png";
img.width = 100;
img.height = 40;
var p1 = document.createElement("p");
p1.setAttribute("class", "bus-number");
p1.innerHTML = number;
var p2 = document.createElement("p");
p2.setAttribute("class", "route");
p2.innerHTML = route;
curr.appendChild(img);
curr.appendChild(p1);
curr.appendChild(p2);
if (buses.length) {
buses[buses.length - 1].insertAdjacentHTML("afterEnd", curr.outerHTML)
} else {
document.forms[0].insertAdjacentHTML("afterEnd", curr.outerHTML)
}
}
var obj = {
company: "",
number: "",
route: ""
};
document.forms[0].onchange = function(e) {
obj[e.target.name] = e.target.value;
}
document.forms[0].onsubmit = function(e) {
e.preventDefault();
addBus(obj.company, obj.number, obj.route)
}
}
plnkr http://plnkr.co/edit/mLz2pNROV3cSCPmnE2S1?p=preview
You can use jQuery to create the new bus div and append it to it's container:
// get these from the form...
var newBusNumber = 123;
var newRoute = "Jefferson";
// create new bus div
var $busDiv = jQuery("<div></div>");
$busDiv.addClass("bus");
$busDiv.addClass("active");
// create img tag
var $img = jQuery("<img />");
$img.attr("src", "img/carta.png");
$img.attr("width", "100");
$img.attr("height", "4");
// create first paragraph tag
var $p1 = jQuery("<p></p>");
$p1.addClass("bus-number");
$p1.text(newBusNumber);
// create second paragraph tag
var $p2 = jQuery("<p></p>");
$p2.addClass("route");
$p2.text(newRoute);
// put the bus div pieces together
$busDiv.append($img);
$busDiv.append($p1);
$busDiv.append($p2);
// append the bus div to it's container
var $busContainer = jQuery(".bus-container");
$busContainer.append($busDiv);
Use JQuery AJAX.After successfull callback append whatever you want .
I think you can just clone the required 'bus', and append it to the container, something like that.
function addBus() {
var id = document.querySelector('input[name="number"]').value; // the index of chosen bus;
var bus = document.querySelectorAll(".bus")[id]; // get chosen bus
var newBus = bus.cloneNode(true); // deep cloning of the existing 'bus'
document.querySelector('.bus-container').appendChild(newBus); // add to the container
}
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>");
}