Unable to retain the table values after refreshing the browser window - javascript

Created a form using html, javascript. After entering the fields, when i click submit button, it saves the user data in localstorage and updates the table rows dynamically. But once i refresh the browser, the table holding the information of all users is lost. I want to retain the table after refreshing the browser.
Click here to view screenshot of page Before refresh
Click here to view screenshot of page After refresh
JS Code :
var testObject = [];
var users = {};
function clear(){
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username,usermail,password,location,organization,gender){
if(username!="" && usermail!="" && password!="" && location!="" && organization!="" && gender!=""){
return true;
}
}
function removeDivChild(str)
{
if(document.getElementById(str).querySelector('p')){
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val,cdiv)
{
if(val=="" && document.getElementById(cdiv).querySelector('p')==null)
{
var node = document.createElement("P");
if(document.getElementById(cdiv).className=="textbox"){
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
}
else if(document.getElementById(cdiv).className=="radiobox"){
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if(val!="" && document.getElementById(cdiv).querySelector('p')!=null)
{
document.getElementById(cdiv).lastElementChild.remove();
}
}
function save(){
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if(document.getElementById("m").checked){
genval = document.getElementById("m").value;
}
if(document.getElementById("f").checked)
{
genval = document.getElementById("f").value;
}
if(IsValid(userval,eval,passval,locval,orgval,genval))
{
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
updateTable();
}
else
{
appendToDiv(userval,"userdiv");
appendToDiv(eval,"maildiv");
appendToDiv(passval,"passdiv");
appendToDiv(locval,"locdiv");
appendToDiv(orgval,"orgdiv");
appendToDiv(genval,"gendiv");
}
}
function updateTable(){
localStorage.setItem("user", JSON.stringify(testObject));
var usr = JSON.parse(localStorage.getItem('user'));
var i = testObject.length-1;
if(i==0){
var nodeh = document.createElement("tr");
var usernode = document.createElement("th");
var usertext = document.createTextNode("Username");
usernode.appendChild(usertext);
nodeh.appendChild(usernode);
var enode = document.createElement("th");
var etext = document.createTextNode("Email");
enode.appendChild(etext);
nodeh.appendChild(enode);
var pnode = document.createElement("th");
var ptext = document.createTextNode("Password");
pnode.appendChild(ptext);
nodeh.appendChild(pnode);
var lnode = document.createElement("th");
var ltext = document.createTextNode("Location");
lnode.appendChild(ltext);
nodeh.appendChild(lnode);
var onode = document.createElement("th");
var otext = document.createTextNode("Organization");
onode.appendChild(otext);
nodeh.appendChild(onode);
var gnode = document.createElement("th");
var gtext = document.createTextNode("gender");
gnode.appendChild(gtext);
nodeh.appendChild(gnode);
document.getElementById("t").appendChild(nodeh);
}
var noder = document.createElement("tr");
var nodeu = document.createElement("td");
var textu = document.createTextNode(usr[i].uname);
nodeu.appendChild(textu);
noder.appendChild(nodeu);
var nodee = document.createElement("td");
var texte = document.createTextNode(usr[i].email);
nodee.appendChild(texte);
noder.appendChild(nodee);
var nodep = document.createElement("td");
var textp = document.createTextNode(usr[i].pass);
nodep.appendChild(textp);
noder.appendChild(nodep);
var nodel = document.createElement("td");
var textl = document.createTextNode(usr[i].loc);
nodel.appendChild(textl);
noder.appendChild(nodel);
var nodeo = document.createElement("td");
var texto = document.createTextNode(usr[i].org);
nodeo.appendChild(texto);
noder.appendChild(nodeo);
var nodeg = document.createElement("td");
var textg = document.createTextNode(usr[i].gender);
nodeg.appendChild(textg);
noder.appendChild(nodeg);
document.getElementById("t").appendChild(noder);
clear();
}
HTML code :
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
</head>
<body>
<script src="check.js"></script>
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male"/> Male
<input type="radio" name="gender" id="f" value="female"/> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<table id="t" border="1">
</table>
</body>
</html>

After the back and forth in the comments on your question I decided to just create an example from your code sample. Most of it was untouched however I did add comments to the things that I did change.
// I moved the declaration of the testObject below to let the functions be created first
// so i can use teh new loadFromStorage function to create the object
var users = {};
// This is a new function I created
function loadFromStorage() {
// parse the 'user' object in local storage, if its empty return an empty array
return JSON.parse(localStorage.getItem('user')) || [];
}
function clear() {
// I didn't touch this function
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username, usermail, password, location, organization, gender) {
// I didn't touch this function
if (username != "" && usermail != "" && password != "" && location != "" && organization != "" && gender != "") {
return true;
}
}
function removeDivChild(str) {
// I didn't touch this function
if (document.getElementById(str).querySelector('p')) {
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val, cdiv) {
// I didn't touch this function
if (val == "" && document.getElementById(cdiv).querySelector('p') == null) {
var node = document.createElement("P");
if (document.getElementById(cdiv).className == "textbox") {
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
} else if (document.getElementById(cdiv).className == "radiobox") {
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if (val != "" && document.getElementById(cdiv).querySelector('p') != null) {
document.getElementById(cdiv).lastElementChild.remove();
}
}
// Changes in this function
function save() {
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if (document.getElementById("m").checked) {
genval = document.getElementById("m").value;
}
if (document.getElementById("f").checked) {
genval = document.getElementById("f").value;
}
if (IsValid(userval, eval, passval, locval, orgval, genval)) {
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
// Saving testObject to the persistent storage here because this is where it belongs
localStorage.setItem("user", JSON.stringify(testObject));
updateTable();
} else {
appendToDiv(userval, "userdiv");
appendToDiv(eval, "maildiv");
appendToDiv(passval, "passdiv");
appendToDiv(locval, "locdiv");
appendToDiv(orgval, "orgdiv");
appendToDiv(genval, "gendiv");
}
}
// Changes in this function
function updateTable() {
// pulled out the saving and the loading of user from localStorage here,
// everything should already be saved or loaded by the time we call
// this function.
// Also re-wrote this function because it was messy and hard to read, always remember you write code for humans not computers so slightly longer variable names that are descriptive are really good.
// get a reference to the table
var tbl = document.getElementById('t');
// remove all the child rows, except for the header
// CSS Selector explained:
// #t - find the table by the id (you used t)
// > tr > td - find all td's that are direct children of the t table
Array.prototype.forEach.call(document.querySelectorAll('#t > tr > td'), function(node) {
node.parentNode.removeChild( node );
})
// loop over all the 'users' in 'testObject'
for(var i = 0; i < testObject.length; i++){
// store a reference to the current object to make the code easier to read
var currentObject = testObject[i];
// create the TR
var tr = document.createElement('tr');
// Create the td's
var tdUserName = document.createElement('td');
var tdEmail = document.createElement('td');
var tdPassword = document.createElement('td');
var tdLocation = document.createElement('td');
var tdOrganization = document.createElement('td');
var tdGender = document.createElement('td');
// create the text nodes
var userName = document.createTextNode(currentObject.uname);
var email = document.createTextNode(currentObject.email);
var password = document.createTextNode(currentObject.pass);
var location = document.createTextNode(currentObject.loc);
var organization = document.createTextNode(currentObject.org);
var gender = document.createTextNode(currentObject.gender);
// add the elements to their containers
tdUserName.appendChild(userName);
tdEmail.appendChild(email);
tdPassword.appendChild(password);
tdLocation.appendChild(location);
tdOrganization.appendChild(organization);
tdGender.appendChild(gender);
// add the td's to the row
tr.appendChild(tdUserName);
tr.appendChild(tdEmail);
tr.appendChild(tdPassword);
tr.appendChild(tdLocation);
tr.appendChild(tdOrganization);
tr.appendChild(tdGender);
// add the row to the table
tbl.appendChild(tr);
}
// call your clear function
clear();
}
// load the object from storage
var testObject = loadFromStorage();
// populate the table
updateTable();
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male" /> Male
<input type="radio" name="gender" id="f" value="female" /> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<!-- Added the header to the table, it isn't removed now when rebuilding it -->
<table id="t" border="1">
<thead>
<tr>
<td>Username</td>
<td>Email</td>
<td>Password</td>
<td>Location</td>
<td>Organization</td>
<td>Gender</td>
</tr>
</thead>
</table>
Here is a link to a JSFiddle because this example wont run properly because it accesses localStorage but is sandboxed. Working Example

Related

i have a form to input data in and i want the data to appear at another page from local storage

my problem is I console log the local storage and the inputs appear fine but I can't see them on the other page although at local storage they are stored fine
the form :
<form id="formID">
<div class="Contact__Card">
<div class="Input__Container">
<label for="foodName" class="Label" >Food</label>
<input
name="foodName"
class="Input"
type="text"
placeholder="What would you like to add?"
id="foodName"
required
/>
</div>
<div class="input__Container">
<label for="foodType">Choose Food type:</label>
<select class="Input" id="foodType" name="foodlist">
<option value="Fruit and vegetables">Fruit and vegetables</option>
<option value="Starchy food">Starchy food</option>
<option value="Dairy">Dairy</option>
<option value="Protein">Protein</option>
<option value="Fat">Fat</option>
</select></div>
<div class="Input__Container">
<label for="price" class="Label">price</label>
<input type="text" min="1" step="any" class="Input" id="foodPrice" required/>
</div>
<br>
<div class="Input__Container">
<input type="submit" value="Submit" class="Input"/>
</div>
</div>
</form>
the js file of the form page :
"use strict";
var allFood = [];
function food(foodName, foodType, price) {
this.foodName = foodName;
this.foodType = foodType;
this.price = price;
allFood.push(this);
}
food.prototype.fID = function () {
this.id = Math.floor(1111 + Math.random() * 9999);
};
const formEl = document.getElementById("formID");
formEl.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
event.preventDefault();
let foodName = event.target.foodName.value;
let foodType = event.target.foodType.value;
let price = event.target.foodPrice.value;
const newFood = new food(foodName, foodType, price);
newFood.fID();
saveData();
}
function saveData() {
let stringifiedData = JSON.stringify(allFood);
localStorage.setItem("Food", stringifiedData);
}
the table of the other page i want the data to apear in :
<table id="fTable">
<tr id="hdrTable">
</tr>
</table>
the js file of the output page is the issue from the get data function ?:
"use strict";
const fdTable = document.getElementById('fTable');
const tableHead = document.getElementById('hdrTable');
var allFood = [];
function food(foodName, foodType, price) {
this.foodName = foodName;
this.foodType = foodType;
this.price = price;
allFood.push(this);
}
food.prototype.fID = function () {
this.id = Math.floor(1111 + Math.random() * 9999);
};
table();
function table() {
let headerID = document.createElement("th");
headerID.textContent = "ID";
let headerName = document.createElement("th");
headerName.textContent = "Food Name";
let headerType = document.createElement("th");
headerType.textContent = "Type of Food";
let headerPrice = document.createElement("th");
headerPrice.textContent = "price";
hdrTable.appendChild(headerID);
hdrTable.appendChild(headerName);
hdrTable.appendChild(headerType);
hdrTable.appendChild(headerPrice);
}
food.prototype.Render = function () {
let row = document.createElement("tr");
let id = document.createElement("td");
let name = document.createElement("td");
let type = document.createElement("td");
let price = document.createElement("td");
id.textContent = this.id;
name.textContent = this.foodName;
type.textContent = this.foodType;
price.textContent = this.price;
row.appendChild(id);
row.appendChild(name);
row.appendChild(type);
row.appendChild(price);
fTable.appendChild(row);
};
getData();
function getData(){
let retrivedData = localStorage.getItem("stringifiedData");
let parsedData = JSON.parse(retrivedData);
if(parsedData!=null){
for (let i = 0; i < parsedData.length; i++) {
let newFoodOP = new food(
parsedData[i].foodName,
parsedData[i].foodType,
parsedData[i].price
);
}
}
for (let i = 0; i < allFood.length; i++) {
allFood[i].Render();
}
console.log(allFood);
}

How to dynamically create variable with loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
How to re-write this code with loop?
var einput1 = document.querySelector("#email0").value;
var einput2 = document.querySelector("#email1").value;
var einput3 = document.querySelector("#email2").value;
and also how to access a specific variable from that loop? Thank You.
Edit:-
Here is demo-
//fuction to genrate email field
function emailGen() {
var quant = document.getElementById("quantity").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (a = 0; a < quant; a++) {
var emailGen = document.createElement("input");
emailGen.type = "email";
emailGen.id = "email" + a;
emailGen.placeholder = "Member's Email";
container.appendChild(emailGen);
}
}
var form = document.getElementById("nameForm");
// event
form.addEventListener("submit", tableGen);
//function for table generator
function tableGen(e) {
e.preventDefault();
var body = document.getElementsByTagName("body")[0];
var table = document.createElement("table");
var tblbody = document.createElement("tbody");
var input1 = document.querySelector("#input1").value;
var quan = document.querySelector("#quantity").value;
//my question is here :-how to make this loop
var einput1 = document.querySelector("#email0").value;
var einput2 = document.querySelector("#email1").value;
var einput3 = document.querySelector("#email2").value;
//table rows loop
for (i = 0; i <= quan; i++) {
var tblrow = document.createElement("tr");
//table coloumn loop
for (j = 0; j < 1; j++) {
var tbldata = document.createElement("td");
if (i == 0 && j == 0) {
var pname = document.createTextNode(input1);
tbldata.appendChild(pname);
}
if (i == 1 && j == 0) {
var tname = document.createTextNode(einput1);
tbldata.appendChild(tname);
}
if (i == 2 && j == 0) {
var tname = document.createTextNode(einput2);
tbldata.appendChild(tname);
}
if (i == 3 && j == 0) {
var tname = document.createTextNode(einput3);
tbldata.appendChild(tname);
}
tblrow.appendChild(tbldata);
}
tblbody.appendChild(tblrow);
}
table.appendChild(tblbody);
body.appendChild(table);
table.setAttribute("border", "4");
}
<form id="nameForm">
<input type="text" id="input1" placeholder="Name"><br/>
<input type="number" id="quantity" name="quantity" placeholder="Total Members(max 10)" min="1" max="10">
<button type="button" id="okButton" onclick="emailGen()"> OK </button>
<div id="container"></div>
<br/>
<input type="submit" value="submit" onsubmit="tableGen()">
</form>
It only show table when input is 3 because declared variable are 3 (at the starting of question) and if I want to submit 1 or 2 field , it does not get submitted. if there is any way to create variable from loop and access it like I did here (einput1)
var tname = document.createTextNode(einput1);
You need to give the emails a name to submit them
Also I removed the onsubmit form the submit button. It does not belong there and can be removed. You have a submit event handler and that should do it
const container = document.getElementById("container");
document.getElementById("nameForm").addEventListener("submit", tableGen);
document.getElementById("okButton").addEventListener("click", emailGen);
//fuction to genrate email field
function emailGen() {
const quant = document.getElementById("quantity").value;
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (let i = 0; i < quant; i++) {
var emailGen = document.createElement("input");
emailGen.type = "email";
emailGen.id = "email" + i;
emailGen.name = "email" + i;
emailGen.placeholder = "Member's Email";
container.appendChild(emailGen);
}
}
//function for table generator
function tableGen(e) {
e.preventDefault();
const body = document.querySelector("body");
const table = document.createElement("table");
const tblbody = document.createElement("tbody");
const input1 = document.getElementById("input1").value;
const quan = document.getElementById("quantity").value;
const emails = container.querySelectorAll("[type=email]")
console.log(emails.length)
//table rows loop
for (let i = 0; i < quan; i++) {
const tblrow = document.createElement("tr");
for (let j = 0; j < emails.length; j++) {
const tblcell = document.createElement("td");
//table column loop
const pname = document.createTextNode(input1);
tblcell.appendChild(pname);
const tname = document.createTextNode(emails[j].value);
tblcell.appendChild(tname);
tblrow.appendChild(tblcell);
}
tblbody.appendChild(tblrow);
}
console.log
table.appendChild(tblbody);
body.appendChild(table);
table.setAttribute("border", "4");
}
<form id="nameForm">
<input type="text" id="input1" placeholder="Name"><br/>
<input type="number" id="quantity" name="quantity" placeholder="Total Members(max 10)" min="1" max="10">
<button type="button" id="okButton">OK</button>
<div id="container"></div>
<br/>
<input type="submit" value="submit">
</form>
Previous answer
document.getElementById("emailForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submit
const quan = +document.getElementById("quan").value
const addr = Array.from({length: quan}, (_, i) => `<input id="email${i}" type="email" placeholder="email${i}" />`)
this.innerHTML += addr.join('<br/>')
})
<form id="emailForm">
<input type="number" min=1 max=10 id="quan" /><br/>
</form>
You can use a loop & string interpolation to achieve the desired results.
The inputs array stores DOM nodes and then you can iterate over this to get the value as in the console.log below OR you can store the values in the input array if you don't want the DOM nodes anymore.
const quan = 3;
const inputs = Array.from({ length: quan }, (_, index) =>
document.querySelector(`#email${index}`)
);
console.log(inputs.map((inp) => inp.value));
<input id="email0" type="email" value="value0">
<input id="email1" type="email" value="value1">
<input id="email2" type="email" value="value2">

Manipulation of div elements with javascript

Can someone explain to me or figure it out. I dont know where I made a mistake here. I have javascript and html code where I get input from user for a flight. I want to make a counter to count all flights function counter() but it gives me the value of name. And another problem is I want when I click on the Accept button to make the background of the div element green function changeColor().
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
var btn1 = document.createElement("BUTTON");
var btn2 = document.createElement("BUTTON");
var t1 = document.createTextNode("Accept");
var t2 = document.createTextNode("Reject");
btn1.appendChild(t1);
btn2.appendChild(t2);
divForOutput.innerHTML += name.value +", " + plainNum.value +"<br>" + "Radius: " + radius.value +", "+"Altitude: "+altitude.value+"<br>"+type.value+"<br>";
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
btn1.setAttribute('onclick','changeColor(this);');
btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
var parentofChild = document.getElementById("output");
output.div.background = green;
}
function counter(){;
var sum = document.getElementsByClassName("printing");
var counter = 0;
for(var i = 0;i <sum.length;i++){
counter+=parseInt(sum[i].innerHTML);
}
document.getElementById("total").innerHTML = counter;
}
<h1>Register flight</h1>
<form>
<div>
<label>Name and surname</label>
<input type="text" id="name">
</div>
<div>
<label>Number plate</label>
<input type="text" id="plainNum">
</div>
<div>
<label>Coordinates</label>
<input type="text" id="coordinates">
</div>
<div>
<label>Radius</label>
<input type="text" id="radius">
</div>
<div>
<label>Altitude</label>
<input type="text" id="altitude">
</div>
<div>
<label>Type</label>
<select id="type">
<option value="Comercial">Comercial</option>
<option value="Buissines">Buissines</option>
</select>
</div>
<div>
<input type="button" value="Submit" onclick="addRow();">
</div>
</form>
<divи>
<h3>Registered flights</h3>
<p>Total:<span id="total">0</span></p>
</div>
<div id="output">
</div>
Below I've fixed some of the code and made things a bit better.
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
//var btn1 = document.createElement("BUTTON");
//var btn2 = document.createElement("BUTTON");
//var t1 = document.createTextNode("Accept");
//var t2 = document.createTextNode("Reject");
//btn1.appendChild(t1);
//btn2.appendChild(t2);
divForOutput.innerHTML = `
${name.value}<br>
Radius: ${radius.value}<br>
Altitude: ${altitude.value}<br>
${type.value}<br>
<button onclick="changeColor();">Accept</button>
<button onclick="disableButtons();">Reject</button>
`;
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
//btn1.setAttribute('onclick','changeColor(this);');
//btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
const output = document.getElementById("output");
output.style.backgroundColor = "green";
}
function counter(){;
const sum = document.getElementsByClassName("printing");
const counter = sum.getElementsByTagName('div').length;
return document.getElementById("total").innerHTML = counter;
}
There is an explanation for the background color here
As for the counter; what I did was count the div elements inside of the output div. That will give you the amount of flights a user has.
Your color setting had several problems. You don't use output.div.background to set the color, and you were using the undefined variable green instead of the string "green". This works:
function changeColor(){
var output = document.getElementById("output");
output.style.backgroundColor = 'green';
}
I don't know what you are trying to count with your counter function, so I can't fix that.

textarea isn't reading input that I have made [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
So no matter what I change if I input anything in the textarea it is not reading anything from the form.
I needed it to be able to have input and not just change the default message of the textarea. If there is any other error in my code please help me by correcting me. And this is only purely html and javascript.
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").innerHTML;
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").innerHTML = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
Try value instead of innerHTML for textarea control.
function findReplace() {
var str = document.getElementById("message").value; //use value here
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res; //use value here
}
Note: There is no element with id demo in the HTML which is used in your JS.
Demo:
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").value;
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
//document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">

Delete row dynamically in JavaScript

I'm doing a form (a simple WEB form, based on the scripts from Tom Negrino, JavaScript 8, and w3Schools) where the user press the Submit button and some of the fields from the form are displayed in one table under the form.
This is the result
Form
Now, I want to delete the row , but only the row that the user wants to delete clicking on the corresponding row.
This is my JavaScript
window.onload = initForms;
function initForms() {
for (var i=0; i< document.forms.length; i++) {
document.forms[i].onsubmit = validForm;
}
document.getElementById("sunroof").onclick = doorSet;
document.getElementById("estado").selectedIndex = 0;
document.getElementById("estado").onchange = populateDays;
/***********/
//document.getElementsByTagName("form")[0].onsubmit = addNode;
/***********/
document.getElementById("env").onclick = function() {
myFunction()
};
}
function validForm() {
var allGood = true;
var allTags = document.getElementsByTagName("*");
for (var i=0; i<allTags.length; i++) {
if (!validTag(allTags[i])) {
allGood = false;
}
}
return allGood;
function validTag(thisTag) {
var outClass = "";
var allClasses = thisTag.className.split(" ");
for (var j=0; j<allClasses.length; j++) {
outClass += validBasedOnClass(allClasses[j]) + " ";
}
thisTag.className = outClass;
if (outClass.indexOf("invalid") > -1) {
invalidLabel(thisTag.parentNode);
thisTag.focus();
if (thisTag.nodeName == "INPUT") {
thisTag.select();
}
return false;
}
return true;
function validBasedOnClass(thisClass) {
var classBack = "";
switch(thisClass) {
case "":
case "invalid":
break;
case "reqd":
if (allGood && thisTag.value == "") {
classBack = "invalid ";
}
classBack += thisClass;
break;
case "radio":
if (allGood && !radioPicked(thisTag.name)) {
classBack = "invalid ";
}
classBack += thisClass;
break;
case "email":
if (allGood && !validEmail(thisTag.value)) classBack = "invalid ";
break;
case "isNum":
case "isZip":
classBack += thisClass;
break;
default:
if (allGood && !crossCheck(thisTag,thisClass)) {
classBack = "invalid ";
}
classBack += thisClass;
}
return classBack;
}
function crossCheck(inTag,otherFieldID) {
if (!document.getElementById(otherFieldID)) {
return false;
}
return (inTag.value != "" || document.getElementById(otherFieldID).value != "");
}
function validEmail(email) {
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return re.test(email);
}
function radioPicked(radioName) {
var radioSet = "";
for (var k=0; k<document.forms.length; k++) {
if (!radioSet) {
radioSet = document.forms[k][radioName];
}
}
if (!radioSet) {
return false;
}
for (k=0; k<radioSet.length; k++) {
if (radioSet[k].checked) {
return true;
}
}
return false;
}
/****Veamos si esto funciona****/
/*function checkboxPicked(checkboxName) {
var checkboxSet = "";
for (var k = 0; k < document.forms.length; k++) {
if (!checkboxSet) {
checkboxSet = document.forms[k][checkboxName];
}
}
if (!checkboxSet) {
return false;
}
for ( k = 0; k < checkboxSet.length; k++) {
if (checkboxSet[k].checked) {
return true;
}
}
return false;
}*/
/*****************************************/
function invalidLabel(parentTag) {
if (parentTag.nodeName == "LABEL") {
parentTag.className += " invalid";
}
}
}
}
function populateDays() {
var tamps = new Array("Ikon Hatch", "Fiesta", "Focus", "Mustang");
var nvoleon = new Array("Aveo", "Spark");
var slp = new Array("Gol", "CrossFox", "Clasico", "Jetta");
var estado = document.getElementById("estado");
var estadoStr = estado.options[estado.selectedIndex].value;
if (estadoStr != "") {
var valueEst = parseInt(estadoStr);
document.getElementById("ciudad").options.length = 0;
if (valueEst == 0) {
for (var i = 0; i < tamps.length; i++) {
document.getElementById("ciudad").options[i] = new Option(tamps[i]);
}
} else if (valueEst == 1) {
for (var i = 0; i < nvoleon.length; i++) {
document.getElementById("ciudad").options[i] = new Option(nvoleon[i]);
}
} else if (valueEst == 2) {
for (var i = 0; i < slp.length; i++) {
document.getElementById("ciudad").options[i] = new Option(slp[i]);
}
}
} else {
document.getElementById("ciudad").options.length = 0;
document.getElementById("ciudad").options[0] = new Option("Model");
}
}
function doorSet() {
if (this.checked) {
document.getElementById("twoDoor").checked = true;
}
}
/*****************************/
/*function addNode() {
var inText = document.getElementById("estado").value;
var inText1 = document.getElementById("ciudad").value;
var newText = document.createTextNode(inText);
var newText1 = document.createTextNode(inText1);
var newGraf = document.createElement("table");
newGraf.appendChild(newText);
newGraf.appendChild(newText1);
var docBody = document.getElementsByTagName("body")[0];
docBody.appendChild(newGraf);
return false;
}*/
function myFunction() {
var table = document.getElementById("myTable");
var email= document.getElementById("emailAddr").value;
var brand=document.getElementById("estado").value;
var model=document.getElementById("ciudad").value;
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = email;
cell2.innerHTML = model;
cell3.innerHTML = brand;
}
And my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Formulario</title>
<link rel="stylesheet" href="css/script06.css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap-theme.min.css">
<!--No se te olvide el css-->
<!--<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap-theme.min.css">-->
<script src="js/script08.js"></script>
<!--No se te olvide el js-->
</head>
<body>
<header></header>
<main>
<article>
<p>
<h1>Choose your car</h1>
</p>
</article>
<form action="#">
<p>
<label for="emailAddr">Email Address:
<input id="emailAddr" type="text" size="40" class="reqd email">
</label>
</p>
<p>
<label for="passwd1">Password:
<input type="password" id="passwd1" class="reqd">
</label>
</p>
<p>
<label for="passwd2">Repeat Pass:
<input type="password" id="passwd2" class="reqd passwd1">
</label>
</p>
<!--<p>
<label for="color">Colors:
<select id="color" class="reqd">
<option value="" selected>Choose a color</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select> </label>
</p>-->
<p>
Options: <label for="sunroof">
<input type="checkbox" id="sunroof" value="Yes">
Sunroof (Two door only)</label>
<label for="pWindows">
<input type="checkbox" id="pWindows" value="Yes">
Power Windows</label>
</p>
<p>
Doors: <label for="DoorCt"><!--Doors: -->
<input type="radio" id="twoDoor" name="DoorCt" value="twoDoor" class="radio">
Two</label>
<label for="DoorCt">
<input type="radio" id="fourDoor" name="DoorCt" value="fourDoor" class="radio">
Four </label>
</p>
<p>
<label>Brand:</label>
<select id="estado" class="reqd">
<option value="">Brand</option>
<option value="0">Ford</option>
<option value="1">Chevrolet</option>
<option value="2">Volkswagen</option>
</select>
<select id="ciudad" class="reqd">
<option>Model</option>
</select>
</p>
<p>
<input type="submit" value="Enviar" id="env">
<input type="reset">
</p>
</form>
<br />
<!--Veamos si funciona-->
<table id="myTable">
<tr>
<td>Email</td>
<td>Model</td>
<td>ID Brand</td>
</tr>
<tr>
</tr>
</table>
</main>
<footer></footer>
</body>
</html>
I tried adding and extra cell in the JavaScript:
cell4.innerHTML = <button onclick="myDeleteFunction()">Del</button>;
where calls the function
function myDeleteFunction() {
document.getElementById("myTable").deleteRow();
}
to delete to row, but it didn't work.
I'll appreciate any help. Thanks.
var node = nodes[0];
if (univArray[z].ownership != "public") {
node.parentNode.removeChild(node)
}
If you want to delete a table row based on a click on the row, you can use something like:
<tr onclick="this.parentNode.removeChild(this)">
If you want to do that based on a button in the row, then:
<tr>
<td><button onclick="deleteRow(this)">Delete this row</button>
Then the deleteRow function is:
function deleteRow(element) {
var row = upTo(element, 'tr');
if (row) row.parentNode.removeChild(row);
}
A helper function
// Return first ancestor of el with tagName
// or undefined if not found
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
// Many DOM methods return null if they don't
// find the element they are searching for
// It would be OK to omit the following and just
// return undefined
return null;
}
The deleteRow function can be put anywhere inside a row, and the row can be in any type of table section element (head, body or foot). All you need to do is to pass a reference to any element inside the row (button, checkbox, cell, whatever).
The trouble with the table.deleteRow method is that you have to know the row index in the element that you're calling the method on. Rows have a rowIndex property that is their index in the table they are in, so you have to go up to the table to use that (i.e. row.parentNode.parentNode), whereas using the removeChild method doesn't require you to work out where in the table the row is, or to even know whether the parent is a head, body or foot section.
Edit
To add the listener dynamically, you can slightly modify the function and add a class to the buttons that will delete rows, e.g.
<!-- Sample markup -->
<table>
<tr>
<td><input type="button" class="rowDeleter" value="Delete Row">
<tr>
<td><input type="button" class="rowDeleter" value="Delete Row">
<tr>
<td><input type="button" class="rowDeleter" value="Delete Row">
</table>
Adding a class means you can easily identify the elements to add the listener to.
<script>
window.onload = function() {
// querySelectorAll and addEventListener require IE 8 or higher, use some other
// method if support for older browsers is required
var els = document.querySelectorAll('.rowDeleter');
for (var i=0, iLen=els.length; i<iLen; i++) {
els[i].addEventListener('click', deleteRow, false);
}
}
// When attached using addEventListener, this in the function
// will be the element that called the listener
function deleteRow() {
var row = upTo(this, 'tr');
if (row) row.parentNode.removeChild(row);
}
// Previously shown helper
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
return null;
}
</script>

Categories

Resources