How to delete firebase child data in Javascript? - javascript

The script is like this to show the data from firebase database:
const onChildAdd = (snap) => { $('#contacts').append(contactHtmlFromObject(snap.key, snap.val()));}
//prepare contact object's HTML
const contactHtmlFromObject = (key, contact) => `
<div class="card contact" style="width: 100%;" id="${key}">
<div class="card-body">
<button class="arrival btn btn-danger btn-xs" onclick="delete_user()">X</button>
<h5 class="card-title">User: ${contact.a2}</h5>
<h6 class="card-subtitle mb-2 text-muted">User1: ${contact.a3}</h6>
<p class="card-text" title="${contact.a1}">
Expiry:${contact.a1} - Vip:${contact.a4} - Status:${contact.a5}
</p>
<input type="text" class="form-control" id="kea" value="${contact.a7}">
</div>
</div>`;
const spanText = (textStr, textClasses) => { const classNames = textClasses.map(c => `text-${c}`).join(' ');
return `<span class="${classNames}">${textStr}</span>`;}
I also have a function:
function delete_user() { firebase.database().ref().child("contact/" + auth.uid + "/" + $('#kea').val()).remove();
alert('The user is deleted successfully!'); }
I use input text to show my child key -Kvhovcjoggiobhuoy something like this or whatever.
I'm trying to delete child key with function delete_user() when click the button.
Any way to correct it, or any other way to delete it?

Related

How to make the second Function await until the first function gets done?

I am a JavaScript beginner, and trying to figure out how to make appendElement wait until createForm done, without using setTomeout(). As createForm is, a div pop up with a button fires updateValues(). I want to appendElement to wait until updatesValues() sets localStorage values so that change on localStorage is going ot be reflected. AppendItem creates card based on values in localStorage. Currently, I have to refresh the page to see the result on local storage. I tried to use async, but appendElement would never wait.
Let me know your insight. Thanks!
Create form
JS
async function addPlace (){
await createForm(idNum);
appendElement("listParent", idNum)
idNum += 1
};
async function createForm(number){
console.log(`locationName_${number}`)
let items = `key, phone, book,...`
let newForm = `
<div id="container" class="d-flex align-items-stretch">
<div class="reveal-modal d-flex flex-column bd-highlight mb-3" id="exampleModal">
<div class="mb-3 d-flex flex-column ">
<label for="locationName" class="form-label">Location</label>
<input type="name" class="form-control" id="updateLocationName_${number}" placeholder="Location Name">
<label for="Lost items" class="form-label">Lost items<br>Please separate items with comma (,)</label>
<input type="name" class="form-control" id="updatedLocationItems_${number}" placeholder="${items}">
</div
<div>
<button class="btn btn-primary" onclick="deleteListCard('\container\')">Cancel</button>
<button class="btn btn-primary" onclick="updateValues(${number})">Add</button>
</div>
</div>
</div>
`
const parentDom = document.querySelector('body')
parentDom.innerHTML += newForm
await updateValues(number)
}
async function updateValues(number){
console.log(`${number} is updated!`)
let updatedName = document.getElementById(`updateLocationName_${number}`).value
let updatedItems = document.getElementById(`updatedLocationItems_${number}`).value
console.log(updatedName)
console.log(updatedItems)
const itemArr = updatedItems.split(',')
// set Array
localStorage.setItem(`locationName_${number}`, updatedName)
localStorage.setItem(`locationItems_${number}`, JSON.stringify(itemArr))
deleteListCard('container') //exit popup
}
//Appned List
function appendElement(parentID, number){
const parentDom = document.getElementById(parentID)
if(document.getElementById("stevens_barbar")){
deleteListCard("stevens_barbar")
}
let location = localStorage.getItem(`locationName_${number}`)
let storedItems = JSON.parse(localStorage.getItem(`locationItems_${number}`))
parentDom.innerHTML += `
<div id="location_${number}">
<h1>${location}</h1>
${generateCheckbox(storedItems)}
<div>
<button class="btn btn-primary" onclick="updateLocalstorage('${number}')">Edit</button>
<button class="btn btn-warning delete_button" onclick="deleteListCard('\location_${number}\')">Delete</button>
</div>
</div>
`
}
await createForm(idNum);
The awaited function is supposed to return a Promise, but createForm doesn't. There is nothing in your code that requires or manipulates promises and everything runs synchronously (except probably for deleteListCard which we don't see). No need for asyns/await.

we use api to fetch numbers between 1 to 5. For example you will get 4 as input from API then you have to activate first four anchor tags

Frist we have to create five anchor tags in that, we use api to fetch numbers between 1 to 5. For example you will get 4 as input from API then add active class to first four anchor tags and in another case like you get 3 as input then add active class to first 3 anchor tags.
let url = "http://localhost:3000/api/hygiene";
let main = document.querySelector(".insert");
let cardData = "";
/*get request*/
fetch(url)
.then(res => res.json())
.then(data => {
data.forEach(function(item,index){
cardData += `
<div class="card my-2 mx-2 product_card" style="width: 18rem;">
<img src="http://localhost:3000/product/${item.image[0].filename}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">${item.title}</h5>
<h6 class="card-subtitle mb-2 text-muted">${item.category}</h6>
<div class="rate ">
★
★
★
<a href="#!" >★</a>
<a href="#!" >★</a>
</div>
<p class="card-text">${item.sortDescription}</p>
</div>
<div class="card-body d-flex">
<div class="price">
<span class="before">₹${item.before}</span>
<span class="current">₹${item.after}</span>
</div>
more
</div>
</div>`;
})
main.innerHTML = cardData;
})
.catch((e)=>{
console.log(e)
})
Add class in this tag
<div class="rate ">
★
★
★
<a href="#!" >★</a>
<a href="#!" >★</a> </div>
I found correct answer and its work
let url = "http://localhost:3000/api/hygiene"
let main = document.querySelector(".insert");
let module = document.querySelector(".moduls");
let rate = document.querySelector(".rate");
let star = "";
let cardData = "";
let detailsData = "";
/*get request*/
fetch(url)
.then(res => res.json())
.then(data => {
data.forEach(function(item,index){
let noStar = Number(item.star) // declare no of elements you want to add active class
cardData += `
<div class="card my-2 mx-2 product_card" style="width: 18rem;">
<img src="http://localhost:3000/product/${item.image[0].filename}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">${item.title}</h5>
<h6 class="card-subtitle mb-2 text-muted">${item.category}</h6>
${stars()} // call function to add elements
<p class="card-text">${item.sortDescription}</p>
</div>
<div class="card-body d-flex">
<div class="price">
<span class="before">₹${item.before}</span>
<span class="current">₹${item.after}</span>
</div>
more
</div>
</div>`;
function stars(){
function starArr(){
let starsArr = [];
for (let i = 1; i <= 5; i++) {
starsArr.push(
`★ `
);
}
return starsArr.join("")
}
return `<div class="rate ">${starArr()}</div>`;
}
})
main.innerHTML = cardData;
})
.catch((e)=>{
console.log(e)
})
Code 👆
You can use the concept of conditionally rendering the element based on the value from the API
Note: I've just added a background color on the stars, you can customize it accordingly.
Here's the link: https://stackblitz.com/edit/react-mtm3nz?file=src%2FApp.js
Refer to the following code
import React, { useState, useEffect } from 'react';
import './style.css';
const totalStars = 5;
const App = () => {
const [starCount, setStarCount] = useState(0);
useEffect(() => {
// make your API call here and setStarCount to the value received
setStarCount(2); // do this after you have your result from the API
}, []);
const renderStars = () => {
let starsArr = [];
for (let i = 1; i <= totalStars; i++) {
starsArr.push(
<a key={i} href="#!" className={i <= starCount ? 'active' : ''}>
★
</a>
);
}
return starsArr;
};
return <div className="rate ">{renderStars()}</div>;
};
export default App;

How can I have multiple functions in onkeyup?

I am writing code to be able to search multiple fields within cards that pull customer data from endpoints. The first function that searches customerID works fine, but I would also like to be able to search the other fields. But I am having trouble getting it recognize multiple fields.
How can I register multiple functions inside an onkeyup field and if I am selecting the forename field in querySelector properly?
My HTML code:
<div class="container pt-3 pb-3">
<div class="form-outline" id="customer-search-bar">
<input type="search" id="filter" class="form-control" placeholder="Enter customer ID" aria-label="Search" onkeyup="searchID() && searchForename();" >
</div>
<div class="card-lists" id="card-lists">
<div class="row">
{% for data in raw.CustomerDataEntries %}
<div class="card col-sm-12 mb-3" id="card-perim">
<div class="card-body" id="card-body">
<h5 class="card-title">Customer ID: {{ data.ExternalId }}</h5>
<h5 class="card-title" name="forename">Forename: {{ data.Fields.forename }}</h5>
<h5 class="card-title">Surname: {{ data.Fields.surname }}</h5>
<h5 class="card-title">Postcode: {{ data.Fields.post_code }}</h5>
<h5 class="card-title">Matches: {{ data.Matches }}</h5>
Details
Edit
</div>
</div>
{% endfor %}
</div>
</div>
</div>
My JavaScript code:
function searchID() {
const input = document.getElementById('filter').value.toUpperCase();
const cardContainer = document.getElementById('card-lists');
console.log(cardContainer);
const cards = cardContainer.getElementsByClassName('card-body');
console.log(cards);
for (let i = 0; 0 < cards.length; i++){
let title = cards[i].querySelector(".card-body h5.card-title");
if(title.innerText.toUpperCase().indexOf(input) > -1){
cards[i].style.display = "";
} else {
cards[i].style.display = "none";
}
}
}
function searchForename() {
const input = document.getElementById('filter').value.toUpperCase();
const cardContainer = document.getElementById('card-lists');
console.log(cardContainer);
const cards = cardContainer.getElementsByClassName('card-body');
console.log(cards);
for (let i = 0; 0 < cards.length; i++){
let title = cards[i].querySelector(".card-body h5[name='forename']");
if(title.innerText.toUpperCase().indexOf(input) > -1){
cards[i].style.display = "";
} else {
cards[i].style.display = "none";
}
}
}
The value within the onkeyup attribute follows JS syntax, so you should separate the statements with a semi-colon, ;.
<input type="search" id="filter" onkeyup="searchID(); searchForename();" class="form-control" placeholder="Enter customer ID" aria-label="Search" />
However using inline event handlers is not good practice. Modern best practice is to unobtrusively bind your event handlers. In native JS you can achieve this by using addEventListener(), like this:
let filter = document.querySelector('#filter');
filter.addEventListener('keyup', () => {
searchID();
searchForename();
});
function searchID() {
console.log('searchID');
}
function searchForename() {
console.log('searchForename');
}
<input type="search" id="filter" class="form-control" placeholder="Enter customer ID" aria-label="Search" />
The second function searchForename() still doesn't work for me though
The main reason it doesn't work is partly because it's a duplication of the work being done in searchId(), so anything displayed by searchId() will be hidden in searchForname().
In addition, because you set display state for every .card-item in the card. This means that if the last item does not contain the searched text the entire card is hidden - even if a previous card did contain the text. To fix this hide the card to start with, then display it only if a match is found.
Here's a working example with the search logic corrected - note that I commented out searchForename() in the keyup handler as it works on a subset of the same
elements as searchID, so its use there is redundant.
let filter = document.querySelector('#filter');
filter.addEventListener('keyup', () => {
searchID();
//searchForename();
});
function searchID() {
const input = filter.value.toUpperCase();
const cardContainer = document.querySelector('#card-lists');
const cards = cardContainer.querySelectorAll('.card-body');
cards.forEach(card => {
card.style.display = 'none';
card.querySelectorAll(".card-body h5.card-title").forEach(title => {
if (title.innerText.toUpperCase().indexOf(input) > -1) {
card.style.display = "block";
}
});
});
}
function searchForename() {
const input = filter.value.toUpperCase();
const cardContainer = document.querySelector('#card-lists');
const cards = cardContainer.querySelectorAll('.card-body');
cards.forEach(card => {
card.style.display = 'none';
card.querySelectorAll(".card-body h5.card-title.forename").forEach(title => {
if (title.innerText.toUpperCase().indexOf(input) > -1) {
card.style.display = "block";
}
});
});
}
<div class="container pt-3 pb-3">
<div class="form-outline" id="customer-search-bar">
<input type="search" id="filter" class="form-control" placeholder="Enter customer ID" aria-label="Search" />
</div>
<div class="card-lists" id="card-lists">
<div class="row">
<div class="card col-sm-12 mb-3">
<div class="card-body">
<h5 class="card-title">Customer ID: 123</h5>
<h5 class="card-title forename">Forename: Lorem</h5>
<h5 class="card-title">Surname: Ipsum</h5>
<h5 class="card-title">Postcode: 90210</h5>
<h5 class="card-title">Matches: Foobar</h5>
Details
Edit
</div>
</div>
<div class="card col-sm-12 mb-3">
<div class="card-body">
<h5 class="card-title">Customer ID: 123</h5>
<h5 class="card-title forename">Forename: Dolor</h5>
<h5 class="card-title">Surname: Sit</h5>
<h5 class="card-title">Postcode: 92893</h5>
<h5 class="card-title">Matches: Fizzbuzz</h5>
Details
Edit
</div>
</div>
</div>
</div>
</div>
My JS code:
One last thing - note that I removed the id attributes in the content you create in the loop. This is because repeated id are invalid, they must contain unique values within the DOM.

How to create dynamicaly a card in NuxtJS

I am new at NuxtJS and I was wondering how to create a v-card through a v-dialog box.
For example, I create an add button then a v-dialog opens then I fill up the form then I "submit" and finally a v-card with what I filled before is created.
Thank you for your help.
I think this will solve you'r problem:
In you'r script:
data() {
return {
formInfo: {
title: '',
description: ''
}
}
},
methods: {
onSubmit() {
let container = document.getElementById('card-container');
this.formInfo.forEach((result, i) => {
// Create card element
let card = document.createElement('v-card');
card.classList = 'you'r classes';
// Construct card content
const content = `
<div class="card">
<div class="card-header" id="heading-{i}">
<h5 class="mb-0">
<button class="btn btn-link">
</button>
</h5>
</div>
<div id="collapse-{i}" class="collapse show">
<div class="card-body">
<h5>{result.title}</h5>
<p>{result.description}</p>
</div>
</div>
</div>
`;
// Append newly created card element to the container
container.innerHTML += content;
})
}
}

how to remove a list item in a list which uses cloud firestore and javascript [duplicate]

This question already has answers here:
Remove elements onclick (including the remove button itself) with jQuery
(3 answers)
Closed 2 years ago.
function renderlist(doc) {
const listmon = document.querySelector("#item-list");
db.collection("cafes")
.get()
.then((snapshot) => {
list(snapshot.docs);
});
const list = (data) => {
let html = "";
data.forEach((doc) => {
const guide = doc.data();
auth.onAuthStateChanged((user) => {
if (user) {
const li = `<li class=${user.uid}>
<div class="card">
<a
href="#"
class="btn btn-fix text-left"
data-toggle="modal"
data-target="#exampleModal"
>
<div class="card-block">
<h4 class="card-title text-dark">${guide.name}</h4>
<p class="card-text text-dark">
${guide.city}
</p>
<a href="#" class="btn btn-primary" id="delete" onclick="arun (){
console.log("clicked");
};">delete</a>
<p class="card-text">
<small class="text-muted">Last updated 3 mins ago</small>
</p>
</div>
</a>
</div>
</li>
<div
class="modal "
id="exampleModal"
tabindex="-1"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button
type="button"
class="close"
data-dismiss="modal"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
</div>
<div
class="modal-body"
data-toggle="modal"
data-target="#exampleModal"
>
${guide.name}
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
data-dismiss="modal"
>
Close
</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>`;
html += li;
listmon.innerHTML = html;
} else {
console.log("logged out");
}
});
});
};
}
i created it using javascript and i want to remove it by clicking a button also i have used user uid as the lists id, when ever i click the button it should remove the list and from cloud firestore it would also be great if somebody could tell me how to only show users data to that particular user,sorry for the language and thanks in advance
I created this simple example to list users with the methods add, delete and show info.
These Firestore/firebase documents [Queries | Modify a document | resource parts ] can be helpful for you to understand better the methods that I used, please feel free to modify this code.
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-firestore.js"></script>
</head>
<body>
<h1>Users</h1>
<div class="content">
<form id="add-user-form">
<input type="text" name="name" placeholder="user Name">
<input type="text" name="location" placeholder="user Location">
<button type="submit">Submit</button>
</form>
<ul id="user-list">
<div id="loader">Loading...</div>
</ul>
</div>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const userList = document.querySelector("#user-list");
const form = document.querySelector("#add-user-form");
//add listener to form, to create new users and avoid default form action
form.addEventListener("submit", e => {
e.preventDefault();
db.collection("users").add({
name: form.name.value,
location: form.location.value
});
form.name.value = "";
form.location.value = "";
});
//Create the users list with the firestore data
function renderuser(doc) {
//creating html elements
let li = document.createElement("li");
let name = document.createElement("span");
let del = document.createElement("button");
let info = document.createElement("button")
//add docuemnt ID to the list element
li.setAttribute("data-id", doc.id);
name.textContent = doc.data().name ;
location.textContent = doc.data().location;
//labels of the buttons
// i= info and x= delete user
info.textContent="i"
del.textContent = "X";
// add onclick action to the buttons
del.onclick=function(){deleteUser(doc.id);}
info.onclick=function(){getData(doc.id);}
// add elements to the list element
li.appendChild(name);
li.appendChild(del);
li.appendChild(info);
// add list element to the list
userList.appendChild(li);
}
function deleteUser(id){
db.collection("users")
.doc(id)
.delete();
}
// Getting Data
function getData(id) {
// __name__ is the reference for the id in firestore
db.collection("users").where("__name__", "==", id).get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc)
//this alert simulate the modal
alert("name: "+doc.data().name+"\nlocation: "+doc.data().location)
});
})
}
//this is not used but this is the method to update the data of a docuemnt(User)
function updateData(id,name,location){
db.collection("users").doc(id).set({
name: name,
location: location
}).then(function() {
alert("Document successfully written!");
})
.catch(function(error) {
alert("Error writing document: ", error);
});
}
// Realtime listener
// this function keep updated the list
function getRealtimeData() {
document.querySelector("#loader").style.display = "block";
//query all users
db.collection("users")
.orderBy("name")
.onSnapshot(snapshot => {
document.querySelector("#loader").style.display = "none";
let changes = snapshot.docChanges();
changes.forEach(change => {
if (change.type === "added") {
//add new users to the list on frist load this create the list of existent users
renderuser(change.doc);
} else if (change.type === "removed") {
//if an user is deleted this will remove the element of the list
let li = userList.querySelector(`[data-id=${change.doc.id}]`);
userList.removeChild(li);
}
});
});
}
//first run
getRealtimeData();
</script>
</body>
</html>

Categories

Resources