I have the following function to get and display data from firebase, create buttons to change the value of 'read' from a book
function readBooksSaved() {
firebase.database().ref('books').orderByChild('author').on('value', function(snapshot){
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
//alert(childData)
let key = childSnapshot.key
let b_title = childSnapshot.val().title;
let b_author = childSnapshot.val().author;
let b_page = childSnapshot.val().page;
let b_read = childSnapshot.val().read;
const u = document.querySelector('#container-li');
let a = document.createElement('li');
let b = document.createElement('li');
let c = document.createElement('li');
let d = document.createElement('li');
const li = document.createElement('li');
const button = document.createElement('a')
const button2 = document.createElement('a')
a.innerHTML = `<strong>Title:</strong> ${b_title}`;
b.innerHTML = `<strong>Author:</strong> ${b_author}`;
c.innerHTML = `<strong>Pages:</strong> ${b_page}`;
button.innerHTML = `Erase`;
if (b_read) {
b_read = 'Yes'
status = 'Unread'}
else {
b_read = 'No' }
d.innerHTML = `<strong>Read</strong> ${b_read}`;
button2.innerHTML = `<a class="btn btn-primary" id="change">${status}</a>`;
u.appendChild(a).classList.add("bg-info");
u.appendChild(b).classList.add("list-group-item");
u.appendChild(c).classList.add("list-group-item");
u.appendChild(d).classList.add("list-group-item");
u.appendChild(button).classList.add("list-group-item");
u.appendChild(button2).classList.add("list-group-item");
let change_bt = document.querySelector('#change')
change_bt.addEventListener('click', changeReadStatus(key, b_read))
});
});
}
function changeReadStatus(key, b_read){
let db_firebase = firebase.database().ref('books/'+ key)
if (b_read) {
db_firebase.update({'/read': false})
}
else {
db_firebase.update({'/read': true})
}
}
Everytime the page loads it enters to the changeReadStatus function and when click on the button the value or 'read' doesn't change on firebase. ¿Could you help me, please? I think I have some errors on the code but I have try without success.
Try this code:
function changeReadStatus(key, b_read){
let db_firebase = firebase.database().ref('books/'+ key);
if(b_read){
db_firebase.update({
'read': true
});
}
else{
db_firebase.update({
'read': false
});
}
}
You should be using the set() function, like this:
function changeReadStatus(key, b_read){
let db_firebase = firebase.database().ref('books/'+ key);
db_firebase.set({'read': b_read});
}
Related
Hi guys I am trying to make a small leaderboard app and I am having problems saving the values in the form. When I try to push the information to the array it is empty and I am rendering nothing, Any help would be appreciated.
Also, my local storage isn't working properly any help on that would also be appreciated.
#Javascript
const form = document.querySelector('.form');
const scores = JSON.parse(localStorage.getItem('scores')) || [];
function saveScore() {
const name = document.querySelector('.fullname').value;
const score = document.querySelector('.thescore').value;
const newScore = {
name,
score,
};
scores.push(newScore);
localStorage.setItem('scores', JSON.stringify(scores));
}
function renderScores() {
const scoreList = document.querySelector('.result-list');
scoreList.innerHTML = '';
scores.forEach((score) => {
const li = document.createElement('li');
li.innerHTML = `${score.name} : ${score.score}`;
scoreList.appendChild(li);
localStorage.setItem('scores', JSON.stringify(scores));
});
}
form.addEventListener('submit', (e) => {
e.preventDefault();
saveScore();
renderScores();
localStorage.setItem('scores', JSON.stringify(scores));
});
You have to put the saveScore function in the eventListener.
This will set the name and score in local storage.
const form = document.querySelector('.form');
const scores = JSON.parse(localStorage.getItem('scores')) || [];
form.addEventListener('submit', (e) => {
e.preventDefault();
// inside now
saveScore();
});
function saveScore() {
const name = document.querySelector('.fullname').value;
const score = document.querySelector('.thescore').value;
const newScore = {
name,
score,
};
scores.push(newScore);
localStorage.setItem('scores', JSON.stringify(scores));
}
I think saveScore(); never happen. Could you try invoke saveScore(); after e.prevendDefault() inside event callback.
Then after event 'submit' will happen you will trigger the saveScore and save values. I hope that will help.
Do it like this:
var arr = [];
function saveScore() {
const name = document.querySelector('.fullname').value;
const score = document.querySelector('.thescore').value;
var newScore = {};
newScore.name = name;
newScore.score = score;
arr.push(newScore);
localStorage.setItem('arr', JSON.stringify(scores));
}
i have a ajax chat with laravel and every thing going okay when i open the chat but when i get new message the all old message repeated too , so i write a statement to prevent that because the normal is when i enter the page the chat load all old messages and when come any new message should append it not append the all old messages
if(chat_history.childElementCount !== data.messages.length)
but when i send any new message the statement will be false so what's solution here please
function getMessages(route,theTeacher) {
let chat_history = document.querySelector('#chat_history');
let options = {
method: 'GET',
headers: {
'Content-Type':
'application/json;charset=utf-8',
'X-CSRF-TOKEN':
document.head.querySelector("[name=csrf-token]").content
},
}
fetchRes = fetch(`${route}/${theTeacher}`, options);
fetchRes.then((response) => {
return response.json()
})
.then((data) => {
if(chat_history.childElementCount !== data.messages.length)
{
for (let c in data.messages) {
if(data.messages[c].sender.indexOf('admin') > -1) {
let liTwo = document.createElement("li");
let message_data = document.createElement("div");
let message_data_span = document.createElement("span");
let my_messages = document.createElement("div");
liTwo.classList.add('clearfix');
message_data.classList.add('message-data', 'text-right')
my_messages.classList.add('message', 'my-message');
message_data_span.classList.add('message-data-time');
message_data_span.innerText = data.messages[c].created_at;
message_data.innerHTML = message_data_span.outerHTML;
my_messages.innerText = data.messages[c].message;
liTwo.appendChild(message_data);
liTwo.appendChild(my_messages);
chat_history.append(liTwo);
// message_data_img.src = d
}
if (data.messages[c].sender.indexOf('teacher') > -1) {
let li = document.createElement("li");
let message_data = document.createElement("div");
let message_data_span = document.createElement("span");
let message_data_img = document.createElement("img");
let other_message = document.createElement("div");
li.classList.add('clearfix');
message_data.classList.add('message-data', 'text-right')
other_message.classList.add('message','other-message', 'float-right')
message_data_span.classList.add('message-data-time');
message_data_span.innerText = data.messages[c].created_at;
message_data_img.src = 'http://127.0.0.1/twaqah-project/twaqah/public/storage/' + data.teacher.avatar;
message_data.innerHTML = message_data_span.outerHTML + message_data_img.outerHTML;
other_message.innerText = data.messages[c].message;
li.appendChild(message_data);
li.appendChild(other_message);
chat_history.append(li);
// message_data_img.src = d
}
}
}
});
}
the blade code
setInterval(function() {
getMessages('{{route('chat.teacher-get-messages')}}',{{request()->teacher}});
}, 3000);
It's my first to do app with filter method. All of these functions works fine, but I have problem when I'm try search something in second input, when I search for one element I lose the rest of the array. How Can I fix that xD ?
const input = document.querySelector('input')
const add = document.querySelector('.addNew')
const clear = document.querySelector('.clear')
const div = document.querySelector('.container')
const search = document.querySelector('.search')
let words = [];
const newTask = () => { // add new task
if(input.value === '') return;
const li = document.createElement('li')
const pe = document.createElement('p')
const btnsComplete = document.createElement('button')
const btnDelete = document.createElement('button')
div.appendChild(li)
li.appendChild(pe)
li.appendChild(btnsComplete)
li.appendChild(btnDelete)
pe.textContent = input.value
btnsComplete.textContent = 'Done'
btnDelete.textContent = 'Cancel'
input.value = '';
words.push(li)
btnsComplete.addEventListener('click',function(e){ // complete
pe.classList.toggle('line')
})
btnDelete.addEventListener('click',function(e){ //cancel
e.target.parentNode.remove()
words.pop(e.target)
document.querySelector('.info').textContent = `Twoja lista składa się z ${words.length} elementów`
})
document.querySelector('.info').textContent = `Twoja lista składa się z ${words.length} elementów`
}
const clearing =() => { //remove all todos
div.innerHTML = ''
words.length = 0
document.querySelector('.info').textContent = `Twoja lista składa się z ${words.length} elementów`
}
const searchTask = (e) => { //search task
const searchText = e.target.value.toLowerCase();
words = words.filter(li => li.textContent.toLowerCase().includes(searchText))
div.textContent =''
words.forEach(li => div.appendChild(li))
}
search.addEventListener('input', searchTask)
clear.addEventListener('click', clearing)
add.addEventListener('click', newTask)
Each time I refresh the page I've registered, it prints 2 times.
const form = document.querySelector("#todo-form");
const todoInput = document.querySelector("#todo");
const addTodoBtn = document.querySelector(".btn.btn-danger");
const listGroup = document.querySelector(".list-group");
const removeBtn = document.querySelector("#clear-todos");
form.addEventListener("submit",addTodoToUI);
function addTodoToUI(e){
createTodoElement(todoInput.value);
e.preventDefault();
}
function createTodoElement(Name){
if(Name === ""){
}
else{
const elementLi = document.createElement("li");
elementLi.className = "list-group-item d-flex justify-content-between";
const txtNode = document.createTextNode(Name);
elementLi.appendChild(txtNode);
const elementA = document.createElement("a");
elementA.href = "#";
elementA.className = "delete-item";
elementA.innerHTML = "<i class = 'fa fa-remove'></i>";
elementLi.appendChild(elementA);
listGroup.appendChild(elementLi);
addTodoToStorage(Name);
}
}
function getTodosFromStorage(){
let todosArray;
if(localStorage.getItem("todos") === null){
todosArray = [];
}
else{
todosArray = JSON.parse(localStorage.getItem("todos"));
}
return todosArray;
}
function addTodoToStorage(todoName){
let todosArray = getTodosFromStorage();
todosArray.push(todoName);
localStorage.setItem("todos",JSON.stringify(todosArray));
}
document.addEventListener("DOMContentLoaded",addTodoFromStorage);
function addTodoFromStorage(){
let Array1 = getTodosFromStorage();
Array1.forEach(function (todo){
createTodoElement(todo);
});
}
Because for some reason in your createTodoElement you add the item to the localstorage when you are rendering it with addTodoToStorage(Name);
So you need to break the rendering part out from the part where you are also adding a new element.
I have this code to get some text from Firebase Database
var reviewID = 0;
var dataRef = firebase.database().ref("reviews/" + reviewID);
function getReview() {
dataRef.once("value").then(function (snapshot) {
const reviewName = snapshot.val().name;
const reviewText = snapshot.val().text;
const reviewDate = snapshot.val().date;
$('#reviewName').html(reviewName);
$('#reviewText').html(reviewText);
$('#reviewDate').html(reviewDate);
});
};
getReview();
And I have this structure in Firebase.
I want button to change reviewID so I must get different values of reviewName, reviewText and reviewDate. Here is code for this button:
$('#reviewButtonRight').click(function () {
reviewID += 1;
getReview();
});
But it doesn't work. So how can I fix it?
You need to create a new ref each time
var reviewID = 0;
var reviewRef = firebase.database().ref("reviews");
function getReview() {
const review = reviewRef.child(reviewID);
review.once("value").then(function (snapshot) {
const reviewName = snapshot.val().name;
const reviewText = snapshot.val().text;
const reviewDate = snapshot.val().date;
$('#reviewName').html(reviewName);
$('#reviewText').html(reviewText);
$('#reviewDate').html(reviewDate);
});
};
getReview();