How to pass constructor values into the DOM - javascript

Link to codepen.
I have a form that people fill out. On clicking submit I want the data to be entered onto the page.
The empty log array and then Patient constructor:
// Set patient log to empty array
let myLog = [];
// Create patient constructor
function Patient(
name,
date,
primInsurance,
secInsurance,
estimate,
isItCovered,
followUp
) {
this.name = name;
this.date = date;
this.primInsurance = primInsurance;
this.secInsurance = secInsurance;
this.estimate = estimate;
this.isItCovered = isItCovered;
this.followUp = followUp;
}
When you click submit, it runs this function:
function addPatientToList(e) {
// Grab elements
const nameValue = document.querySelector("#name").value;
const dateValue = document.querySelector("#date").value;
const primInsurValue = document.querySelector("#primary-insurance").value;
const secInsurValue = document.querySelector("#secondary-insurance").value;
const estimateValue = document.querySelector("#estimate").value;
const isItCoveredValue = document.querySelector("#covered").value;
const followUpValue = document.querySelector("#follow-up").value;
e.preventDefault();
// Instantiate patient
const patient = new Patient(
nameValue,
dateValue,
primInsurValue,
secInsurValue,
estimateValue,
isItCoveredValue,
followUpValue
);
myLog.push(patient);
renderPatient();
clearFields();
closeModal();
}
After adding the patient to the constructor, it attempts to render to the dom:
function renderPatient() {
const list = document.querySelector("#patient-list");
const row = document.createElement("tr");
row.innerHTML = `
<td>${Patient.name}</td>
<td>${Patient.date}</td>
<td>${Patient.primInsur}</td>
<td>${Patient.secInsurance}</td>
<td>${Patient.estimate}</td>
<td>${Patient.isItCovered}</td>
<td>${Patient.followUp}</td>`;
list.appendChild(row);
}
What shows up in the dom is just 'undefined' across all table rows.

You're referencing the Patient "class" and not the patient "instance", here's the code fixed.
const submitBtn = document.querySelector("#submit");
// Set patient log to empty array
let myLog = [];
var patient;
// Create patient constructor
function Patient(
name,
date,
primInsurance,
secInsurance,
estimate,
isItCovered,
followUp
) {
this.name = name;
this.date = date;
this.primInsurance = primInsurance;
this.secInsurance = secInsurance;
this.estimate = estimate;
this.isItCovered = isItCovered;
this.followUp = followUp;
}
// On click, submit patients to log and clear fields
submitBtn.addEventListener("click", addPatientToList);
function addPatientToList(e) {
// Grab elements
const nameValue = document.querySelector("#name").value;
const dateValue = document.querySelector("#date").value;
const primInsurValue = document.querySelector("#primary-insurance").value;
const secInsurValue = document.querySelector("#secondary-insurance").value;
const estimateValue = document.querySelector("#estimate").value;
const isItCoveredValue = document.querySelector("#covered").value;
const followUpValue = document.querySelector("#follow-up").value;
e.preventDefault();
// Instantiate patient
patient = new Patient(
nameValue,
dateValue,
primInsurValue,
secInsurValue,
estimateValue,
isItCoveredValue,
followUpValue
);
myLog.push(patient);
renderPatient();
clearFields();
closeModal();
console.log(myLog);
}
// Render patient to list
function renderPatient() {
const list = document.querySelector("#patient-list");
const row = document.createElement("tr");
row.innerHTML = `
<td>${patient.name}</td>
<td>${patient.date}</td>
<td>${patient.primInsur}</td>
<td>${patient.secInsurance}</td>
<td>${patient.estimate}</td>
<td>${patient.isItCovered}</td>
<td>${patient.followUp}</td>`;
list.appendChild(row);
}
// Close modal
function closeModal() {
modal.style.display = "none";
}
// Clear fields
function clearFields() {
nameValue = "";
dateValue = "";
primInsurValue = "";
secInsurValue = "";
estimateValue = "";
isItCoveredValue = "";
followUpValue = "";
}
///// Show / hide modal
// Grab the modal / button
const modal = document.querySelector("#modal");
const addBtn = document.querySelector("#add");
const closeBtn = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
addBtn.addEventListener("click", function () {
modal.style.display = "block";
});
// When the user clicks on <span> (x), close the modal
closeBtn.addEventListener("click", function () {
modal.style.display = "none";
});
// Anywhere outside, close modal
window.addEventListener("click", function () {
if (event.target == modal) {
modal.style.display = "none";
}
});

You're not accessing anything when you call Patient.property. You could just pass the patient object to renderPatient.
function addPatientToList(e) {
// Grab elements
const nameValue = document.querySelector("#name").value;
const dateValue = document.querySelector("#date").value;
const primInsurValue = document.querySelector("#primary-insurance").value;
const secInsurValue = document.querySelector("#secondary-insurance").value;
const estimateValue = document.querySelector("#estimate").value;
const isItCoveredValue = document.querySelector("#covered").value;
const followUpValue = document.querySelector("#follow-up").value;
e.preventDefault();
// Instantiate patient
const patient = new Patient(
nameValue,
dateValue,
primInsurValue,
secInsurValue,
estimateValue,
isItCoveredValue,
followUpValue
);
myLog.push(patient);
renderPatient(patient);
clearFields();
closeModal();
console.log(myLog);
}
// Render patient to list
function renderPatient(patient) {
const list = document.querySelector("#patient-list");
const row = document.createElement("tr");
row.innerHTML = `
<td>${patient.name}</td>
<td>${patient.date}</td>
<td>${patient.primInsurance}</td>
<td>${patient.secInsurance}</td>
<td>${patient.estimate}</td>
<td>${patient.isItCovered}</td>
<td>${patient.followUp}</td>`;
list.appendChild(row);
}

The problem is those properties aren't static properties of the Patient class, they are only available from the instance of Patient. You can access them via:
// Instantiate patient
const patient = new Patient(
nameValue,
dateValue,
primInsurValue,
secInsurValue,
estimateValue,
isItCoveredValue,
followUpValue
);
console.log(patient.nameValue); // outputs patient name from modal

Related

I am having trouble pushing form values to an array in a leaderboard app

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));
}

Updating the query data in cloud firestore nested map fields

I'm trying to update the data in nested map fields in firestore, my form is a window form that has 4 sides (wSide1,wSide2,wSide3,wSide4), what my form is doing is if customer select 1 field which is wSide1 and it needs to be updated then only this field only be updated but in my case it is updating all 4 sides, the one which is selected for example side 1 only that has the correct updated values other 3 sides updates with the false values. as my form is dynamic it only shows the field which is selected.
I only want to update the field which is selected, all other has to be null.
js & firestore query
function updateWindowForm(form, type){
var name = $('#name_'+type).val();
var type = $('#type_'+type).val();
const taskformWindow = document.getElementById("taskformWindow");
let editStatus = false;
let id = '';
const updateTask = (id, updatedTask) => db.collection('Buildings').doc(buildingID).collection('rooms').doc(roomID).collection('objects').doc(objectID).update(updatedTask);
window.addEventListener("DOMContentLoaded", async (e) => {
id = doc.id;
editStatus = true;
btnsEdit.forEach((btn) => {
btn.addEventListener("click", async (e) => {
try {
const doc = await getTask(e.target.dataset.id);
const task = doc.data();
editStatus = true;
id = doc.id;
taskformWindow["btn-update-data"].innerText = "Update";
} catch (error) {
console.log(error);
}
});
});
});
taskformWindow.addEventListener("click", async (e) => {
e.preventDefault();
var name_Window = document.getElementById('name_Window').value;
var wAluminium = document.getElementById('wAluminium').checked;
var wColorMeasurement = document.getElementById('wColorMeasurement').value;
var wComments = document.getElementById('wComments').value;
var wForEnd1 = document.getElementById('wForEnd1').checked;
var wForEnd2 = document.getElementById('wForEnd2').checked;
var wSideOfWindows = document.getElementById('wSideOfWindows').value;
var wHardwareManufacturer = document.getElementById('wHardwareManufacturer').value;
var wPlastic = document.getElementById('wPlastic').checked;
//Side 1
var wAxis1_1 = document.getElementById('wAxis1_1').checked;
var wAxis1_2 = document.getElementById('wAxis1_2').checked;
var wBackSet1 = document.getElementById('wBackSet1').value;
var wDirectionLR1_1 = document.getElementById('wDirectionLR1_1').checked;
var wDirectionLR1_2 = document.getElementById('wDirectionLR1_2').checked;
var wHandleHeight1 = document.getElementById('wHandleHeight1').value;
var wOverlapWidth1 = document.getElementById('wOverlapWidth1').value;
var wSashRebateHeight1 = document.getElementById('wSashRebateHeight1').value;
var wSashRebateWidth1 = document.getElementById('wSashRebateWidth1').value;
//Side 2
var wAxis2_1 = document.getElementById('wAxis2_1').checked;
var wAxis2_2 = document.getElementById('wAxis2_2').checked;
var wBackSet2 = document.getElementById('wBackSet2').value;
var wDirectionLR2_1 = document.getElementById('wDirectionLR2_1').checked;
var wDirectionLR2_2 = document.getElementById('wDirectionLR2_2').checked;
var wHandleHeight2 = document.getElementById('wHandleHeight2').value;
var wOverlapWidth2 = document.getElementById('wOverlapWidth2').value;
var wSashRebateHeight2 = document.getElementById('wSashRebateHeight2').value;
var wSashRebateWidth2 = document.getElementById('wSashRebateWidth2').value;
//Side 3
var wAxis3_1 = document.getElementById('wAxis3_1').checked;
var wAxis3_2 = document.getElementById('wAxis3_2').checked;
var wBackSet3 = document.getElementById('wBackSet3').value;
var wDirectionLR3_1 = document.getElementById('wDirectionLR3_1').checked;
var wDirectionLR3_2 = document.getElementById('wDirectionLR3_2').checked;
var wHandleHeight3 = document.getElementById('wHandleHeight3').value;
var wOverlapWidth3 = document.getElementById('wOverlapWidth3').value;
var wSashRebateHeight3 = document.getElementById('wSashRebateHeight3').value;
var wSashRebateWidth3 = document.getElementById('wSashRebateWidth3').value;
//Side 4
var wAxis4_1 = document.getElementById('wAxis4_1').checked;
var wAxis4_2 = document.getElementById('wAxis4_2').checked;
var wBackSet4 = document.getElementById('wBackSet4').value;
var wDirectionLR4_1 = document.getElementById('wDirectionLR4_1').checked;
var wDirectionLR4_2 = document.getElementById('wDirectionLR4_2').checked;
var wHandleHeight4 = document.getElementById('wHandleHeight4').value;
var wOverlapWidth4 = document.getElementById('wOverlapWidth4').value;
var wSashRebateHeight4 = document.getElementById('wSashRebateHeight4').value;
var wSashRebateWidth4 = document.getElementById('wSashRebateWidth4').value;
try {
if (!editStatus) {
await updateTask(id, {
name:name_Window,
Form:{
wAluminium: wAluminium,
wColorMeasurement: wColorMeasurement,
wComments: wComments,
wForEnd1: wForEnd1,
wForEnd2: wForEnd2,
wHardwareManufacturer: wHardwareManufacturer,
wPlastic: wPlastic,
wSide1:{
wAxis1_1: wAxis1_1,
wAxis1_2: wAxis1_2,
wBackSet1: wBackSet1,
wDirectionLR1_1: wDirectionLR1_1,
wDirectionLR1_2: wDirectionLR1_2,
wHandleHeight1: wHandleHeight1,
wOverlapWidth1: wOverlapWidth1,
wSashRebateHeight1: wSashRebateHeight1,
wSashRebateWidth1: wSashRebateWidth1,
},
wSide2:{
wAxis2_1: wAxis2_1,
wAxis2_2: wAxis2_2,
wBackSet1: wBackSet2,
wDirectionLR2_1: wDirectionLR2_1,
wDirectionLR2_2: wDirectionLR2_2,
wHandleHeight2: wHandleHeight2,
wOverlapWidth2: wOverlapWidth2,
wSashRebateHeight2: wSashRebateHeight2,
wSashRebateWidth2: wSashRebateWidth2,
},
wSide3:{
wAxis3_1: wAxis3_1,
wAxis3_2: wAxis3_2,
wBackSet1: wBackSet3,
wDirectionLR3_1: wDirectionLR3_1,
wDirectionLR3_2: wDirectionLR3_2,
wHandleHeight3: wHandleHeight3,
wOverlapWidth3: wOverlapWidth3,
wSashRebateHeight3: wSashRebateHeight3,
wSashRebateWidth3: wSashRebateWidth3,
},
wSide4:{
wAxis4_1: wAxis4_1,
wAxis4_2: wAxis4_2,
wBackSet4: wBackSet4,
wDirectionLR4_1: wDirectionLR4_1,
wDirectionLR4_2: wDirectionLR4_2,
wHandleHeight4: wHandleHeight4,
wOverlapWidth4: wOverlapWidth4,
wSashRebateHeight4: wSashRebateHeight4,
wSashRebateWidth4: wSashRebateWidth4,
},
wSideOfWindows: wSideOfWindows,
}
})
editStatus = false;
id = '';
taskformWindow['btn-update-window-data'].innerText = 'Daten aktualisiert';
swal("", "Daten wurden aktualisert!", "success");
}
taskformWindow.reset();
} catch (error) {
console.log(error);
}
});
}
I can't see the code you use for updating your data but I can ausme that you probably did not set the merge to true while saving the data.
Take a look at this code snipped:
var cityRef = db.collection('cities').doc('BJ');
var setWithMerge = cityRef.set({
capital: true
}, { merge: true });
By setting that we ensure to udate only the fields we want to and leave the rest as it is. Still make sure not to send fields with a null value because that is a valid value for firestore and it doesn't mean that those fields will by skipped in the update process. You can find more about it here.

Updating a value in firebase with javascript not working

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});
}

Problem with to do list. How Can I get back my array?

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, how do I fix it?

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.

Categories

Resources