while saving data to database in Firebase via Web App occurs - javascript

Like if I have these two input boxes.
<input type="button" id="valone">
<input type="button" id="valuetwo">
<button type="submit" onClick="submitB();" id="sbmtbtn">
<script>
const firstval = findViewById="valueone";
const secondval = findViewById="valuetwo";
const submit = findViewById="sbmtbtn";
const first = firstval.value;
const second = secondval.value;
function submitB() {
const firebaseRef = firebase.database().ref().push();
firebaseRef.child("Value").child("Value One").set(first.value);
firebaseRef.child("Value").child("Value Two").set(second.value);
}
But it does this image like .......
It shows blanks not the values of the input box
Please help me all dependencies are set upped correctly and everything is pretty fine.

You're trying to look up the HTML elements, but are using a non-existing function. You're looking for getElementById(), like this:
<input type="button" id="valone">
<input type="button" id="valuetwo">
<button type="submit" onClick="submitB();" id="sbmtbtn">
<script>
const firstElm = findElementById("valueone");
const secondElm = findElementById("valuetwo");
const submitBtn = findElementById("sbmtbtn");
const first = firstElm.value;
const second = secondElm.value;
function submitB() {
const firebaseRef = firebase.database().ref().push();
firebaseRef.child("Value").child("Value One").set(first);
firebaseRef.child("Value").child("Value Two").set(second);
}

Related

Why will my HTML form data not store in a Javascript variable?

I have tried everything online and can't seem to resolve this issue. I am creating a form via DOM in JS and appending it to my HTML file. I want to be able to pull the data out of the form field when it is submitted, but the variable with .value is always empty when i console.log().
addProject creates the form and addOrRemove should store its data when submitted
My code (including some things commented out):
`function addProject(){
const box = document.getElementById("sidebar");
const next = document.createElement("form");
next.classList.add("next");
/*next.innerHTML = `
<input type="text" id="reminder" name="reminder" id="newProject"><br>
<nav>
<button id="add">Add</button>
<button id="cancel" type="submit">Cancel</button>
</nav>
`;*/
next.insertAdjacentHTML('beforeend', ` <input type="text" id="reminder" name="reminder" id="newProject"><br>
<nav>
<button id="add">Add</button>
<button id="cancel" type="submit">Cancel</button>
</nav> `);
box.appendChild(next);
addOrRemove();
};
function projectListener(){
const click = document.getElementById("newProj");
click.addEventListener("click", function(){
addProject()
});
};
function addOrRemove(){
const green = document.getElementById("add");
const red = document.getElementById("cancel");
const form = document.querySelector(".next");
form.addEventListener("submit", function(){
const val = document.getElementById("newProject").value;
console.log(val);
});
/* green.addEventListener("click", function(){
const val = document.getElementById("newProject");
console.log(val.value);
alert(val.value);
if(document.getElementById("newProject").value!=null){
const project = document.createElement("div");
project.innerHTML = `
<div><img src="../src/photos/square.png" alt=""><p>${data}</p></div>
`;
const remove = document.querySelector(".next");
box.remove(remove);
box.appendChild(project);
}
}); */`

calculating from an input

I'm starting studying the DOM in javascript and I'd like to create a program which makes the sum of two numbers given on input and show it.
I'd like to know what functions should I use, and what functions it is better I didn't.
This is my (very simple) html code:
let warp = document.getElementById('warp');
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
let res = document.getElementById('res');
//res.addEventListener('click', calcul);
//res.onclick(calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul(first, second) {
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>
let answerElemenet = document.createElement("h1");
// You can create a h1 element to display your answer after calculating it
document.body.appendChild(answerElemenet);
// Inside the calculate Function you get the values of input one and two
// and then you store the sum value in a variable and just change your
// answerElement to have the innerHTML value of the finalSum Variable
function calculate(){
let valueOne = parseFloat(document.getElementById('first').value);
let valueTwo = parseFloat(document.getElementById('second').value);
let finalSum = valueOne + valueTwo;
answerElemenet.innerHTML = finalSum;
}
Welcome to Stackoverflow!
I copied your answer and made some small changes. Here comes a brief description and explanation of what you could do better:
If you don't plan to change these references use const instead of let. Also try to keep input elements separated from their values. The reference to the input probably won't change but their value most certainly will.
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
When calculating input values, you usually want them as fresh as possible so instead of saving input values right at the beginning of the script, you get them when you need them, in the calcul() function.
You will also need some kind of validation. Here we try to convert the input to a number and set to zero if not possible:
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
The preferred way of adding event handlers to DOM elements is using the event API. So to call the calcul()function you use the line you had commented:
res.addEventListener('click', calcul);
This also means you should remove the onClick attribute from the DOM. Also, input cannot have children:
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
All together looks like this:
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
res.addEventListener('click', calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
</form>
<div>
</body>
Keep up the good job and never stop asking questions!
This will work. You just need to call the values based on their id in the calcul() function itself.
let warp = document.getElementById('warp');
let res = document.getElementById('res');
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul() {
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
if(isNaN(one) || isNaN(two)){
event.preventDefault();
return
}
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>

JSON stringify is showing object object after refresh

inputting the data is fine, submitting is fine. But, if I refresh, everything that was inputted displays as object object. Any idea's why?
In addition to this, each input creates table data but seperately rather than in a table and each input puts each newly created data side by side whereas I want them to space-around like justify-content: space-around. But it doesn't seem to be doing that
Still new to JS. I couldn't find exactly what i'm doing wrong. JSON stringify is still a new practice for me too. So, I am unsure if what I have done is correct.
EDIT ------------------------
Can anyone explain what is happening with the formatting after a refresh ?
html
<h1>Library</h1>
<div id="login" class="login-btn">
<button class="User" id = "login">login</button>
</div>
<button id="clear">Clear</button>
<form id="form" action="">
<input class="input" type="text" id="input-title" placeholder="Title" required />
<input class="input" type="text" id="input-author" placeholder="Author" required/>
<input class="input" type="number" id="input-number" placeholder="Pages" required />
<input value="Submit" id="submitbtn" class="submit" type="submit">
</form>
<input type="checkbox" class="checkbox"><span> Check me if you read the book</span>
<table id="table">
</table>
<script src="script.js"></script>
</body>
</html>
js
//buttons
const buttonLogin = document.getElementById("login")
const table = document.getElementById("table")
const clearBtn = document.getElementById("clear")
const submitBtn = document.getElementById("submitbtn")
const form = document.getElementById("form")
const inputTitle = document.getElementById("input-title")
const inputAuthor = document.getElementById("input-author")
const inputNumber = document.getElementById("input-number")
//array local storage
let itemsArray = localStorage.getItem('items')
? JSON.parse(localStorage.getItem('items'))
: []
localStorage.setItem('items', JSON.stringify(itemsArray))
const data = JSON.parse(localStorage.getItem('items'))
const createBook = (text, text1, text2) => {
const tble = document.createElement('table')
const td = document.createElement('td')
const td2 = document.createElement('td')
const td3 = document.createElement('td')
td.textContent = text
td.style.color = ('black')
td.style.border = ('solid')
td.style.borderColor =('blueviolet')
td2.textContent = text1
td2.style.color = ('black')
td2.style.border = ('solid')
td2.style.borderColor = ('blueviolet')
td3.textContent = text2
td3.style.color = ('black')
td3.style.border = ('solid')
td3.style.borderColor =('blueviolet')
table.appendChild(td)
table.appendChild(td2)
table.appendChild(td3)
}
form.addEventListener('submit', function (e) {
e.preventDefault()
//for (var i = 0; i < 2; i++) {
itemsArray.push(inputTitle, inputAuthor, inputNumber)
localStorage.setItem('items', JSON.stringify(itemsArray))
createBook(inputTitle.value, inputAuthor.value, inputNumber.value)
inputTitle.value = ''
inputAuthor.value= ''
inputNumber.value= ''
// }
})
data.forEach ((item) => {
createBook(item)
})
//clear list
clearBtn.addEventListener('click', function () {
localStorage.clear()
while (table.firstChild) {
table.removeChild(table.firstChild)
}
})
You need to save the values of the inputs, not the input elements themselves. And the values for a single item should be collected together into an array or object.
itemsArray.push([inputTitle.value, inputAuthor.value, inputNumber.value])
Also, when you process the data, you need to spread the array into separate arguments to createBook().
data.forEach ((item) => {
createBook(...item)
})
i think it's relate to this line
itemsArray.push(inputTitle, inputAuthor, inputNumber)
// where
const inputTitle = document.getElementById("input-title")
const inputAuthor = document.getElementById("input-author")
const inputNumber = document.getElementById("input-number")
// should be below if you don't want printout [object Object]
itemsArray.push(inputTitle.value, inputAuthor.value, inputNumber.value)
why '[object Object]'
var array = []
var anchor = document.createElement('a')
array.push(JSON.stringify(anchor)) // -> ['{}']
var anchor2 = document.createElement('a')
anchor2.textContent = JSON.parse('{}')
anchor2.textContent // -> '[object Object]'

How can i get the data from localstorage and view in table using javascript and make a dropdown to sort the table

I have the following code that need to display the id,name and occupation. i can add to local storage but need to display it in table and sort based on name, id and occupation. any idea how can i do it using javascript. sample outputoutput
<!DOCTYPE html>
<html>
<title>Sorting Test</title>
<body>
<fieldset>
<legend>Add participant<legend>
<input id="userID" type="text">
<input id="userName" type="text">
<input id="userOccupation" type="text">
<button id="addbtn" type="button" >Add</button>
</fieldset>
<br>
<div id="displayOutput">
</div>
</body>
<script>
// get the userid, userName and UserOccupation
const userID = document.getElementById("userID");
const userName = document.getElementById("userName");
const userOccupation = document.getElementById("userOccupation");
const addbtn = document.getElementById("addbtn");
const displayOutput = document.getElementById("displayOutput");
//add user input to storage
addbtn.onclick = function(){
const id = userID.value;
const name = userName.value;
const occupation = userOccupation.value;
if(id && name && occupation)
{
let myObj = {
id,
name,
occupation
};
let myObj_serialized = JSON.stringify(myObj);
localStorage.setItem("myObj",myObj_serialized);
}
//view the stored information
for (let i=0; i < localStorage.length; i++)
{
const key = localStorage.key(i);
const value =localStorage.getItem(key);
var row = `<tr><td>${key}: ${value}<td><tr><br/>`;
displayOutput.innerHTML += row;
console.log(value);
}
};
</script>
</html>
You are overriding the stored item values everytime you call setItem. If you want to display a table, I suggest storing an array of objects. If you want to use local storage, Stringify the array before storing and parse it when you need to read it
var storeData = function(data) {
localStorage.setItem("tableData",JSON.stringify(data);
}
storeData([]);
var getData = function() {
return JSON.parse(localStorage.getItem("tableData"));
}
And call something like this to save data:
storeData(getData().push({id: id, name: name, occupation: occupation});
And then to display the data you can do:
var arr = getData();
arr.forEach(element) {
displayOutput.innerHtml += `
<tr>
<td>ID: ${element.id}</td>
<td>Name: ${element.name}</td>
<td>Occupation: ${element.occupation}</td>
</tr>`;
}
As for the sorting, you can call a sort function on the array on the onclick of the table's column header.

Global array remains empty

I am trying to update my global array, but it remains null after I submit a text value(.name) through a submit button.
Please tell me how I can keep track of text values in my global array. Thank you.
var display_name = [];
document.addEventListener('DOMContentLoaded', () =>{
document.querySelector("#form1").onsubmit = () => {
let name = document.querySelector(".name").value;
display_name.push(name);
};
});
When the form is submitted, a new page is loaded. It loads the URL in the action property of the form. So, your variable goes away.
If you don't want that to happen, prevent the form from being submitted with preventDefault.
For example ...
const name_list = [];
window.addEventListener('DOMContentLoaded', (e) => {
const names = document.querySelector(`.names`);
const add_button = document.querySelector(`.names--add_button`);
names.addEventListener('submit', e => e.preventDefault());
add_button.addEventListener('click', (e) => {
const name = document.querySelector(`.names--name`);
const collected = document.querySelector(`.names--collected`);
name_list.push(name.value);
collected.innerHTML += `<li>${name.value}</li>`;
name.value = ``;
name.focus();
});
});
body { background: snow; }
<form class="names" action="#" method="post">
<label>Name: <input type="text" name="name" class="names--name"></label>
<button class="names--add_button">Add To List</button>
<div>Names Collected:</div>
<ul class="names--collected">
</ul>
</form>
I am see at the moment it's working perfect. but you want add value every time when you click the button. so just changed the type of your
<button type="submit"> to <button type="button">
because when you click on submit page automatically reload in html, an the 2nd thing you need to change your event from onsubmit to onclick and your button to it instead of your form.
var display_name = [];
document.addEventListener('DOMContentLoaded', () =>{
document.querySelector("#button1").onclick = () => {
let name = document.querySelector(".name").value;
display_name.push(name);
};
});

Categories