How to save an image (input type="file") into the local storage and display it back onload of a page in javaScript - javascript

I have an input type file and when I click, it will select a particular image, likewise some other input type text which i have to use to collect data from the user and I am as well having a button to set the data into the localStorage once the button is clicked.
Onload of the page, I want the information on the localStorage (productImg, productName, productOldPrice, productCategory, productNewPrice, productSavePrice) to display on the browser.
Note: Every other information are displaying except the productImg which is why am asking this question.
What I wanted to archive is a way of setting each product image into the localStorage and when displaying it on the browser, each product image should be display on the designated place.
<button id="adminSponsorPush" class="btn btn-lg btn-success " style="width: 30%;" onclick="text()">Sponsored Products</button>
<input type="file" id="adminDealImg">
<input type="text" name="" id="adminDealName" placeholder="Product Name">
<input type="text" name="" id="adminOldPrice" placeholder="deals Old Price">
<input type="text" name="" id="adminNewPrice" placeholder="deals new Price">
<button type="button" onclick="setIt()" class="btn btn-primary">Understood</button>
<div id="todaysDeal" class="d-flex flex-wrap w-100 gap-3 p-2 border border-danger border-2"></div>
This is the JavaScript code that set the data into the localStorage
let allProducts = [];
if (localStorage.companyProduct) {
allProducts = JSON.parse(localStorage.getItem("companyProduct"));
}
text = () => {
let products = {
firstName: "",
lastName: "",
email: "",
phoneNumber: "",
password: "",
topDeal: [],
sponsorProduct: [],
recommendedProduct: [],
inspiredProduct: [],
laptops: [],
smartPhone: [],
healthBeauty: [],
groceries: [],
videoGames: [],
mobileAccessories: [],
homeFurnishings: [],
fitnessToolsEquipment: [],
kidsWearAccessories: [],
topDealOnTelevision: [],
};
allProducts.push(products);
localStorage.setItem("companyProduct", JSON.stringify(allProducts));
};
setIt = () => {
for (let index = 0; index < allProducts.length; index++) {
let topDealProduct = {
productImg: adminDealImg.value,
productName: adminDealName.value,
productOldPrice: adminOldPrice.value,
productCategory: `product`,
productNewPrice: adminNewPrice.value,
productSavePrice: `You save ₦${adminOldPrice.value - adminNewPrice.value}`,
};
allProducts[index].topDeal.push(topDealProduct);
localStorage.setItem("companyProduct", JSON.stringify(allProducts));
localStorage.setItem("currentUserIndex", index);
}
};
This is the javaScript code that will display the information into the browser when the page is load
currentProductIndex = localStorage.getItem("currentUserIndex");
displayProducts = () => {
todaysDeal.innerHTML = "";
eachTopDealProduct = allProducts[currentProductIndex].topDeal;
for (let index = 0; index < eachTopDealProduct.length; index++) {
todaysDeal.innerHTML += `
<div onclick="topDealProductPage(${index})" class="d-flex p-3 shadow each-todays-deal gap-3"
style="width: 32.5%; height: 120px; cursor: pointer;"
>
<img src="${eachTopDealProduct[index].productImg}" alt="" id="dealsImg"/>
<div class="d-flex flex-column gap-3">
<div class="text-capitalize" id="dealsProductName">${eachTopDealProduct[index].productName}</div>
<div class="">
<div class="d-flex gap-2">
<div class="fw-bold fs-4" id="dealsPrice">₦${eachTopDealProduct[index].productNewPrice}</div>
<div class="fw-bold fs-6 my-auto text-decoration-line-through text-secondary" id="dealsPrice">₦${eachTopDealProduct[index].productOldPrice}</div>
</div>
<div class="fw-bold" style="font-size: 12px; color: #33B27B;" id="dealsSave">${eachTopDealProduct[index].productSavePrice}</div>
</div>
</div>
</div>
`;
}
};

Get file data from onChange callback and transfer it to base64, then set base64 to LocalStorage.
<input type="file" id="adminDealImg">
<img src="" id="img" alt="">
<script>
if(localStorage.getItem('img-BASE64')){
document.querySelector('#img').src=localStorage.getItem('img-BASE64')
}
function getBase64(file) {
return new Promise((resolve,reject)=>{
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
resolve(reader.result)
};
reader.onerror = reject
})
}
document.querySelector('#adminDealImg').addEventListener('change', async(e)=>{
const data = await getBase64(e.target.files[0])
localStorage.setItem('img-BASE64', data)
})
</script>
After you have changed the question.
Set img data to localStorage is different from normal data.
// error here
productImg: adminDealImg.value,
you can set image base64 data as a unique key and get it by this key as identity, maybe email ?
LocalStorage.setItem(img-Base64-${email}, 'sth base64')
Please click LIKE button. Orz....

Related

How to initiate OnClick event for each search results items so that it render a product page with meta data of that item in Javascript

How to create a onclick event for each search results items so that it render a product page with meta data of that item. I have successfully able to filter items as per keypress. Now I want to give a click event for filtered item to open a product page. How would I do that in Javascript? Please help me figure out this.
**My HTML code**
<!-- Search form -->
<div class="container">
<div class="active-pink-4 mb-4 mt-4">
<input class="form-control form_search" type="text" placeholder="Search" aria-label="Search" id="search">
</div>
<div id="match-list" name="matchid"></div>
</div><!-- End of Search form -->
<div class="container"><!-- Strat of login container-->
<div class="row" id="viewhide"><!-- Strat of login row-->
<div class="col-md-6 d-none d-sm-block"><!--start of col login img-->
<img src="https://img.etimg.com/thumb/width-1200,height-900,imgsize-27424,resizemode-1,msid-14351710/industry/healthcare/biotech/pharmaceuticals/free-medicines-to-all-patients-in-government-hospitals-from-november.jpg">
</div><!--End of col login img-->
<div class="col-md-6 text-center fadeIn first"><!--Start col login-->
<h2>Sign In</h2>
<!-- Login Form -->
<form>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Username">
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
<div id="formFooter">
<a class="underlineHover mb-2" href="#">Forgot Password?</a>
</div>
<input type="submit" class="btn btn-primary d-flex justify-content-center d-md-table mx-auto mb-2 btn-round" value="Login">
<h5>You don't have an account ?</h5>
<input type="button" class="btn btn-primary d-flex justify-content-center d-md-table mx-auto mb-5 btn-round" value="Register">
</form>
</div><!-- End of col login-->
</div><!-- End of login row-->
</div><!-- End of login container-->
**My Js code:**
const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
// Search states.json and filter it
const searchStates = async searchText =>{
const res = await fetch('lib/json/data.json').then(response =>{
//console.log(response);
if (!response.ok) {
throw Error("Error");
}
return response.json();
}).then(data =>{
//console.log(data.item);
let states = data.item;
//console.log(states, "states");
// Get matches to current text input
let matches = states.filter(state =>{
const regex = new RegExp(`^${searchText}`, `gi`);
return state.itemName.match(regex) || state.itemMfrCode.match(regex);
});
let divhide = document.getElementById('viewhide');
if(searchText.length !== 0){
divhide.style.display = "none";
}else{
divhide.style.display = "flex";
}
//Hide all results when input is empty
if (searchText.length === 0) {
matches = [];
matchList.innerHTML = '';
}
//Hide if no results are found
if (searchText !== states) {
match = [];
matchList.innerHTML = '';
}
outputHtml(matches);
}).catch(error =>{
console.log(error);
});
};
//Show results in HTML
const outputHtml = matches => {
if (matches.length > 0) {
const html = matches.map(match => `
<div class="card card-body mb-1" id="medprod" name="selectid"
onclick="getproduct()">
<h4 style="cursor: pointer;">${match.itemName}</h4>
</div>
`).join('');
matchList.innerHTML = html;
}
}
search.addEventListener('input', () => searchStates(search.value));
//On clcik search result items function
function getproduct(){
}
**My Json structure**
{
"clientId": "1234",
"systemId": "2010",
"orderReferenceNo": "43442",
"responseCode": "0000",
"responseDescription": "Items successfully retrieved!",
"item": [
{
"itemMfrCode": "0001001",
"qnty": "00000000",
"itemName": "clinic shampoo",
"unitPk": "30ml",
"itemCategory": " ",
"itemType": "NT",
"schemeRange": "000",
"schemeOffeQty": "000",
"rateDiffFlag": "N",
"schemeHalfValueFlag": " ",
"schemeHalfValuePerc": null,
"ratePerUnit": 20.00
},
{},
}
I should have posted the answer long before. No problem, hope it helps someone in future.
const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
const productLayout = document.getElementById('product_layout');
//Search filter
const searchStates = async searchText => {
const res = await
fetch('https://data.json').then(response => {
if (!response.ok) {
throw Error("Error");
}
return response.json();
}).then(data => {
console.log(data.item);
let states = data.item;
console.log(states, "states");
matchList.style.display = 'block';
// Get matches to current text input
let matches = states.filter(state => {
const regex = new RegExp(`^${searchText}`, `gi`);
return state.itemName.match(regex) ||
state.itemMfrCode.match(regex);
});
if (searchText.length !== 0) {
productLayout.style.display = 'none';
} else {
productLayout.style.display = 'block';
}
outputHtml(matches);
}).catch(error => {
console.log(error);
});
};
//Show results in HTML
const outputHtml = matches => {
if (matches.length > 0) {
//Meta data of clicked item
//Keep adding
//${match.itemId},${match.itemRate},${match.itemColor} to the list.
const html = matches.map(match => `
<li id="${match.itemMfrCode}">${match.itemName}</li>
`).join('');
matchList.innerHTML = html;
}
}
search.addEventListener('input', () => searchStates(search.value));
/*OnClick filtered items*/
matchList.addEventListener('click', function(e) {
var target = e.target;
while (target && target.parentNode !== matchList) {
target = target.parentNode;
if (!target) {
return;
}
}
if (e.target.tagName === 'LI') {
//Get selected product name
let liInnerText = e.target.innerText;
//Store prod name in localStorage
localStorage.setItem('liText', liInnerText);
//Insert selected item in input text field
search.value = liInnerText;
//Hide search dropdown after click event
matchList.style.display = 'none';
/*View product layout*/
productLayout.style.display = 'block';
//Get product name from localStorage
var selectedName = localStorage.getItem('liText');
//Dispaly product name in HTML page
document.getElementById('prod_name').innerHTML =
selectedName;
}
});
#match-list {
display: none;
}
#product_layout {
display: none;
}
<!-- Search form -->
<div class="container" id="search_layout">
<div class="active-pink-4 mb-2 mt-4">
<input class="form-control form_search" type="text" placeholder="Search" aria-label="Search" id="search" value="" autocomplete="off" onfocus="this.value=''">
</div>
<ul id="match-list" name="matchid"></ul>
</div>
<!-- End of Search form -->
<!--Product details-->
<div class="container-fluid" id="product_layout">
<div>
<p id="prod_name"></p>
</div>

HTML Form Select Element Not Allowing Changes

I have a form that I am creating for my kids' school and am having issues with the drop-down list to choose the student name. The list is populated via JavaScript code, importing a student list from an associated google sheet. I added a console log for each option as they are created to show that they are in fact being created. Developer options on the link should reveal that.
Once I load the form I am unable to change the student identifier from the default option. I can't tell what I've done wrong. If I hard code the values into the HTML it works fine, but I want the teacher to be able to add and remove students via the spreadsheet because that is a more user-friendly and flexible implementation.
form.html code
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<style>
body {
background: rgb(244, 235, 234)
}
.outer-field {
border-radius: 15px;
background: white;
height: 150px;
margin: 10px;
padding: 20px;
}
.title {
padding-left: 2%;
font-weight: bold;
}
</style>
</head>
<body>
<div class="row">
<div class="col s8 offset-s2 offset-s2">
<!--Document Header-->
<div class="outer-field" style="height: 100px">
<h4>Golden Apple Reader Book Submissions</h4>
</div>
<!--Form to submit ISBN and autopopulate title and page count-->
<form id="myForm" onsubmit="event.preventDefault(); formSubmit(this) ">
<!--Creates ISBN entry field-->
<div class="outer-field">
<div class="title">Book ISBN</div>
<div class="col s8">
<div class="input-field">
<input type="text" id="ISBN" name="ISBN" class="UUID validate" form="myForm">
<label for="ISBN">ISBN</label>
</div>
</div>
<!--Creates button to check ISBN data-->
<button class="btn waves-effect waves-light" id="btn" style="margin-left: 3%" type="button" onclick="populateDetails(); return false;">Autofill Book Data From ISBN
<i class="material-icons right">send</i>
</button>
</div>
<!--Creates student name entry field-->
<div class="outer-field">
<div class="title">Student Name</div>
<div class="input-field col s12">
<select form="myForm" name="StudentID" id="StudentID" required>
<!--Add student IDs and names here-->
<!--<option value="212702">John</option>
<option value="212703">Henry</option>
<option value="003">003</option>-->
</select>
</div>
</div>
<!--Creates book title entry field-->
<div class="outer-field">
<div class="title">Book Required Information</div>
<div class="col s8">
<div class="input-field">
<input type="text" id="Title" name="Title" class="name" form="myForm" required>
<label for="Title">Book Title</label>
</div>
</div>
<!--Creates book page count entry field-->
<div class="col s4">
<div class="input-field">
<input type="number" id="PageCount" name="PageCount" class="pages" form="myForm" required>
<label for="PageCount">Book Page Count</label>
</div>
</div>
</div>
<!--Creates button to submit data-->
<button class="btn waves-effect waves-light" type="submit" name="action" style="margin-left: 3%" >Submit
<i class="material-icons right">send</i>
</button>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
M.FormSelect.init(document.querySelectorAll('select'));
//function to populate student list element
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById('StudentID');
for( var i=0; i<selectList.length; i++ ) {
//initial attempt commented here for troubleshooting
//var option = document.createElement('option');
//option.value = selectList[i][0];
//option.text = selectList[i][4];
var option = new Option(selectList[i][4], selectList[i][0]);
console.log(option);
select.add(option, undefined);
}
console.log(select)
}
).getSelectList();
}());
//Uses the ISBN to populate the book title and page quantity
function populateDetails(){
isbn=document.getElementById('ISBN').value;
//isbn=9781492680550;//for debugging only
var url = "https://www.googleapis.com/books/v1/volumes?country=US&q=isbn:" + isbn;
var obj
var title="No Entry Identified";
var pageCount=0;
var titleout=document.getElementById('Title');
var pageout=document.getElementById('PageCount');
//fetches URL data from google books API
fetch(url)
.then(res => res.json())
.then(data => obj = data)
.then(
function(settitle){
//Assigns title to variable and text field
title = obj.items[0].volumeInfo.title
titleout.value=title;
titleout.focus();
},
function(titlerror){
})
.then(
function(setpages){
//Assigns page count to variable and text field
pageCount = obj.items[0].volumeInfo.pageCount
pageout.value=pageCount;
pageout.focus();
},
function(pageerror){
})
//In the case that no entry is found in google books API, assigns default values to text fields and deconflicts the overlapping label and value fields
titleout.value=title;
titleout.focus();
pageout.value=pageCount;
pageout.focus();
}
//Submits form data to spreadsheet
function formSubmit (data) {
var dataToSubmit = {
studentID: data.StudentID.value,
title: data.Title.value,
pageCount: data.PageCount.value
}
//Provides a success message to the user
google.script.run.withSuccessHandler(function () {
myForm.reset()
M.toast({html: "Thank you! You have successfully submitted!"})
}).submitData(dataToSubmit)
}
</script>
</body>
</html>
code.gs code
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Submissions")
var ss2= SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Students")
var last=ss2.getLastRow();
var students=ss2.getRange(2,1,last-1,5).getValues();
function getSelectList() {
try {
return students;
}
catch(err) {
Logger.log(err);
}
}
function doGet() {
return HtmlService.createTemplateFromFile('form').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')
}
function submitData (data) {
ss.appendRow([new Date(),data.studentID, data.title, data.pageCount])
}
spreadsheet content:
Student ID Number
Student Name
Teacher Name
Grade
Concatenation
UNK1
John
TeacherA
K
Grade: K, Teacher: TeacherA, Name: John
UNK2
Henry
TeacherA
K
Grade: K, Teacher: TeacherA, Name: Henry
UNK3
Paige
TeacherA
K
Grade: K, Teacher: TeacherA, Name: Paige
UNK4
Raelyn
TeacherA
K
Grade: K, Teacher: TeacherA, Name: Raelyn
UNK5
Danielle
TeacherA
K
Grade: K, Teacher: TeacherA, Name: Danielle
UNK6
Olivia
TeacherA
K
Grade: K, Teacher: TeacherA, Name: Olivia
When I saw your script, I thought that there is a modification point. Please modify as follows.
From:
M.FormSelect.init(document.querySelectorAll('select'));
//function to populate student list element
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById('StudentID');
for( var i=0; i<selectList.length; i++ ) {
//initial attempt commented here for troubleshooting
//var option = document.createElement('option');
//option.value = selectList[i][0];
//option.text = selectList[i][4];
var option = new Option(selectList[i][4], selectList[i][0]);
console.log(option);
select.add(option, undefined);
}
console.log(select)
}
).getSelectList();
}());
To:
//function to populate student list element
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById('StudentID');
for( var i=0; i<selectList.length; i++ ) {
//initial attempt commented here for troubleshooting
//var option = document.createElement('option');
//option.value = selectList[i][0];
//option.text = selectList[i][4];
var option = new Option(selectList[i][4], selectList[i][0]);
console.log(option);
select.add(option, undefined);
}
console.log(select)
M.FormSelect.init(document.querySelectorAll('select')); // Moved.
}
).getSelectList();
}());
In this modification, M.FormSelect.init(document.querySelectorAll('select')) was moved.
I thought that (function () { and }()); might be not required to be used.

VUE JS - Some of my methods are being called without me calling them

I'm having an annoying issue with Vue JS >.< My methods are being called without my approval. I basically have a button that execute a method, but this method execute when other methods are executed, making it very annoying...
Here is my form
<form class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 pr-xl-0 pr-lg-0 pr-md-0 m-b-30">
<div class="product-slider">
<img class="d-block" :src="image" alt="First slide" width="285" height="313">
Image URL <input type="text" #focusout="showPicture" id="imageLink">
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 pl-xl-0 pl-lg-0 pl-md-0 border-left m-b-30">
<div class="product-details">
<div class="border-bottom pb-3 mb-3">
<h2 class="mb-3">
<input type="text" value="Product Name" minlength="4" id="name" required/>
</h2>
<h3 class="mb-0 text-primary">$<input type="number" value="1.00" step="0.01" id="price" required></h3>
</div>
<div class="product-size border-bottom">
<h4>Provider</h4>
<input type="text" value="Pro Inc." minlength="3" id="provider" required>
<div class="product-qty">
<h4>Quantity</h4>
<div class="quantity">
<input type="number" value="1" id="quantity" required>
</div>
</div>
</div>
<div class="product-description">
<h4 class="mb-1">Description</h4>
<textarea rows="4" cols="50" minlength="50" id="description" required>Sample Text</textarea>
<button :onclick="addProduct()" class="btn btn-primary btn-block btn-lg">Add to inventory</button>
</div>
</div>
</div>
</form>
and here is my full script
<script>
const DB_NAME = 'DBInventory';
const DB_VERSION = 1;
export default {
data: function() {
return {
db:null,
ready:false,
addDisabled:false,
image: "https://i.imgur.com/O9oZoje.png",
};
},
async created() {
this.db = await this.getDb();
this.ready = true;
},
methods: {
showPicture() {
let link = document.getElementById("imageLink").value;
if(link !== "")
this.image = link;
},
async getDb() {
return new Promise((resolve, reject) => {
let request = window.indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = e => {
console.log('Error opening db', e);
reject('Error');
};
request.onsuccess = e => {
resolve(e.target.result);
};
request.onupgradeneeded = e => {
console.log('onupgradeneeded');
let db = e.target.result;
let objectStore = db.createObjectStore("products", { autoIncrement: true, keyPath:'id' });
console.log(objectStore);
};
});
},
async addProduct() {
this.addDisabled = true;
let product = {
name: document.getElementById("name").value,
provider: document.getElementById("provider").value,
price: document.getElementById("price").value,
quantity: document.getElementById("quantity").value,
description: document.getElementById("description").value,
image: document.getElementById("imageLink").value,
};
console.log('about to add '+JSON.stringify(product));
await this.addProductToDb(product);
this.addDisabled = false;
},
async addProductToDb(product) {
return new Promise((resolve, reject) => {
//delete me
console.log(reject);
let trans = this.db.transaction(['products'],'readwrite');
trans.oncomplete = e => {
//delete me
console.log(e);
resolve();
};
let store = trans.objectStore('products');
store.add(product);
});
},
}
}
</script>
One of my method execute when you are not focused on the image input field. It works, but also execute the addProduct(), which push my item to my indexDB, something that I want to happen only when I press the button "Add to inventory".
This is very confusing and I'm kinda a noob on Vue JS ^^' (I use Vue 3)
You have the wrong syntax
:onclick="addProduct()"
:onclick should be #click or v-on:click
https://v2.vuejs.org/v2/guide/events.html
To avoid the function to be autoexecuted, you need to provide the onclick method with the function declaration. Try the code below. I don't use Vue, but it works in React. Javascript anyway.
:onclick="() => addProduct()"
Correct syntax for click event in vue
full syntax
<a v-on:click="addProduct"></a>
shorthand syntax
<a #click="addProduct"></a>
Then call method addProduct
addProduct: function () {
...
}

Make calculation from v-for in vue js

i'm trying to make simple calculation from data given in vuejs. The calculation is just going well. But, when i started to make sum from calculation total from it, it keeps returning NaN value.
Here is the current code of it:
<div class="row" v-for="fields in data" :key="field.id_m_all_ded">
<div class="col-md-5">
<div class="form-group">
<label>{{ field.name }}</label>
<input type="field.type" class="form-control" #change="calculated(field)" v-model="field.value" />
</div>
</div>
<div class="col-md-7">
<label>Total Deductions</label>
<input type="number" class="form-control" v-model="field.total" disabled />
</div>
</div>
<div class="row">
<div class="col-md-5">
<label>Total Allowance</label>
<input type="number" class="form-control" v-model="grandTotal" id="total" disabled />
</div>
</div>
I retrieve the data from my API, and it saved in fields[]:
data() {
return {
model: {
nik: "",
name: "",
basic_salary: "",
period: "",
},
modals: {
modal: false,
},
fields: [{
total: ''
}],
totalData: 11,
page: 1,
mode: "",
};
},
And here's the function:
computed: {
grandTotal: function() {
let temp = 0
for (var i = 0; i < this.fields.length; i++) {
temp = temp + Number(this.fields[i].total)
console.log(temp)
}
console.log(temp)
return temp;
}
},
methods: {
calculated(field){
field.total = 4000000 * (field.value / 100)
console.log(field.total)
}
}
For addtional info, i get the data from the api, but it won't calculate automatic. Therefore, i tried it with manual input first to calculate the value.
What code should i fix from it, because i have no clue.
Thanks

Inserting a set of input fields and button from data-id of element

I currently have a form that shows itself after I clicked on a button, and the save button would allow me to save the input values into an object.
What would be a more efficient way to write this function if I need to have 9 more of the same button with different data-id(e.g. data-id="2" and so on), without having to duplicate the function into saveConditionOne,saveConditionTwo,saveConditionThree.
const patient = {}
// Save conditions to object
function saveConditions() {
const missing = document.getElementById('missingVal').value
const movement = document.getElementById('movementVal').value
const tilt = document.getElementById('tiltVal').value
patient.one = {
missing: missing,
movement: movement,
tilt: tilt
}
console.log(patient)
}
<button data-id="1" id="showForm" class="btn">1</button>
<div id="conditionSelect">
<h5>Form</h5>
<div class="field">
<label for="">Missing Tooth</label>
<input type="text" id="missingVal">
</div>
<div class="field">
<label for="">Movement</label>
<input type="text" id="movementVal">
</div>
<div class="field">
<label for="">Tilt</label>
<input type="text" id="tiltVal">
</div>
<button id="saveCondition" onclick="saveConditions()" class="btn btn-primary">Save</button>
</div>
Now
{
"one": {
"missing": "tooth",
"movement": "1mm",
"tilt": "10deg"
}
}
Expected
{
"one": {
"missing": "tooth",
"movement": "1mm",
"tilt": "10deg"
},
"two": {
"missing": "tooth",
"movement": "1mm",
"tilt": "10deg"
},
"three": {
"missing": "tooth",
"movement": "1mm",
"tilt": "10deg"
}
}
I wouldn't use an object for patient (or at least, not for this part of the patient information), I'd use an array. Then you simply push the data onto the array:
patient.push({
missing: missing,
movement: movement,
tilt: tilt
});
...or if you make this a property on the patient object (perhaps there is other, patient-wide information):
patient.entries.push({
missing: missing,
movement: movement,
tilt: tilt
});
Live Example:
const patient = {
entries: []
}
// Save conditions to object
function saveConditions() {
const missing = document.getElementById('missingVal').value
const movement = document.getElementById('movementVal').value
const tilt = document.getElementById('tiltVal').value
patient.entries.push({
missing: missing,
movement: movement,
tilt: tilt
})
console.log(patient)
}
.as-console-wrapper {
max-height: 100% !important;
}
<button data-id="1" id="showForm" class="btn">1</button>
<div id="conditionSelect">
<h5>Form</h5>
<div class="field">
<label for="">Missing Tooth</label>
<input type="text" id="missingVal">
</div>
<div class="field">
<label for="">Movement</label>
<input type="text" id="movementVal">
</div>
<div class="field">
<label for="">Tilt</label>
<input type="text" id="tiltVal">
</div>
<button id="saveCondition" onclick="saveConditions()" class="btn btn-primary">Save</button>
</div>
How about this approach. I've loaded your default form into a template which you can loop over. This means you don't have to hardcode each form directly into the page. I've then added one button which when clicked calls the saveConditions function. This loops over the forms extracting their data and adding it to the data object using a patient id.
const patientCount = 3;
const data = {};
function getFormHTML(id) {
return (
`<div class="conditionSelect" data-id="patient${id}">
<h5>Form</h5>
<div class="field">
<label>Missing Tooth</label>
<input type="text" name="missingVal">
</div>
<div class="field">
<label>Movement</label>
<input type="text" name="movementVal">
</div>
<div class="field">
<label>Tilt</label>
<input type="text" name="tiltVal">
</div>
</div>`
)
}
const html = [];
for (let i = 0; i < patientCount; i++) {
html.push(getFormHTML(i));
}
document.body.insertAdjacentHTML('beforeend', html.join(''));
document.body.insertAdjacentHTML('beforeend', '<button class="saveCondition">Save</button>')
const button = document.querySelector('.saveCondition');
button.addEventListener('click', saveConditions, false);
function getVal(form, name) {
return form.querySelector(`[name=${name}]`).value
}
function saveConditions(e) {
const forms = document.querySelectorAll('.conditionSelect');
forms.forEach(form => {
const patientId = form.dataset.id;
data[patientId] = {
missing: getVal(form, 'missingVal'),
movement: getVal(form, 'movementVal'),
tilt: getVal(form, 'tiltVal'),
};
});
console.log(data);
}

Categories