I want to create contenteditable in div when user add something in it then it should add in local storage. but right now it is overwrite when add another data.
HTMl code
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="checkEdits()">
<div id="edit" contenteditable="true">
Here is the element's original content
</div>
<input type="button" value="save my edits" onclick="saveEdits()" />
<div id="update"> - Edit the text and click to save for next time</div>
<h1 contentEditable="true">Your Name</h1>
<script src="script.js"></script>
</body>
</html>
JS code
function saveEdits() {
//get the editable element
var editElem = document.getElementById("edit");
//get the edited element content
var userVersion = editElem.innerHTML;
//save the content to local storage
localStorage.userEdits = userVersion;
//write a confirmation to the user
document.getElementById("update").innerHTML = "Edits saved!";
}
function checkEdits() {
//find out if the user has previously saved edits
if (localStorage.userEdits != null)
document.getElementById("edit").innerHTML = localStorage.userEdits;
}
You need to change your saveEdits function to check is there anything saved on storage with the same key or not. To achieve it I will recommend you to use get and set item from API here some example how you can do it.
function saveEdits() {
//get the editable element
var editElem = document.getElementById("edit");
//get the edited element content
var userVersion = editElem.innerHTML;
//get previously saved
const previousEditsStr = localstorage.getItem('userEdits');
// parse allready saved edits or create empty array
const savedEdits = previousEditsStr ? JSON.parse(previousEditsStr) : [];
// push the latest one
savedEdits.push(userVersion);
//stringify and save the content to local storage
localStorage.setItem('userEdits', JSON.stringify(savedEdits));
//write a confirmation to the user
document.getElementById("update").innerHTML = "Edits saved!";
}
Please be noticed that the memory here is limited and you need to take it under your control. For example you can limit previously saved comments.
Since we are saving an array thats men you need to change your reading part as well
function checkEdits() {
const userEdits = localStorage.getItem('userEdits');
//find out if the user has previously saved edits
if (userEdits) {
// here is the saved edits
const comments = JSON.parse(userEdits);
// showing previously saved message
document.getElementById("edit").innerHTML = comments[comments.length - 1];
}
}
How can I store localStorage value without losing last value stored on it
I write code to insert row to table contient data from input everytime I click button 'insert new row' but I have issue after fill the table I want use table's data to insert to SQL database table using localStorage and ajax I do it but my problem he give me just data of last row because when I click save he give localStorage new value
<!-- my problem : console.log shows me last item - I want to store all my inputs products without losing previous when I click button save -->
<input type="text" id="products">
<button onclick="myfunction()">save</button>
<script>
function myfunction() {
var products = document.getElementbyid("products").value;
var save_listProducts = localStorage.setItem("data",products);
}
var get_listProducts = localStorage.getItem("data");
console.log(get_listProducts);
</script>
You need to add little bit more code in order to maintain a "list" (array) in localStorage. There is no problem with actually storing an array in localStorage as long as it is a string - and to convert an array into a string ( and be able to parse it back later ) you can use JSON.stringify (and JSON.parse to get it back)
function addNewItem (item) {
let myList = JSON.parse(localStorage.getItem("myList", "[]"));
myList.push(item);
localStorage.setItem("myList", JSON.stringify(myList));
}
function getAllItems () {
return JSON.parse(localStorage.getItem("myList", "[]"));
}
function removeItem (index) {
let myList = JSON.parse(localStorage.getItem("myList", "[]"));
myList.splice(index, 1);
localStorage.setItem("myList", JSON.stringify(myList));
}
👆 This is just an example and would need to be modified to fit your code, please do not just copy/paste it
In your example
<input type="text" id="product">
<button onclick="myfunction()">save</button>
<script>
function myfunction() {
var product = document.getElementbyid("product").value;
addNewItem(product);
console.log(getAllItems());
}
function addNewItem (item) {
var myList = JSON.parse(localStorage.getItem("myList", "[]"));
myList.push(item);
localStorage.setItem("myList", JSON.stringify(myList));
}
function getAllItems () {
return JSON.parse(localStorage.getItem("myList", "[]"));
}
</script>
Im learning JavaScript and Im having problems trying to get the value of HTML of textareaElement. Theres lots online and because of all the information available its making it more confusing. I understand the idea behind the DOM, but not sure how to do the code. I am also trying to use add an event listener to store data in local storage, but without any luck.
// Add a text entry to the page
function addTextEntry(key, text, isNewEntry) {
// Create a textarea element to edit the entry
var textareaElement = document.createElement("TEXTAREA");
textareaElement.rows = 5;
textareaElement.placeholder = "(new entry)";
// Set the textarea's value to the given text (if any)
textareaElement.value = text;
// Add a section to the page containing the textarea
addSection(key, textareaElement);
// If this is a new entry (added by the user clicking a button)
// move the focus to the textarea to encourage typing
if (isNewEntry) {
textareaElement.focus();
// Get HTML input values
var data = textareaElement.value;
}
// ...get the textarea element's current value
var data = textareaElement.value;
// ...make a text item using the value
var item = makeItem("text", data);
// ...store the item in local storage using key
localStorage.setItem(key, item);
// Connect the event listener to the textarea element:
textareaElement.addEventListener('onblur', addTextEntry);
}
HTML is:
<section id="text" class="button">
<button type="button">Add entry</button>
</section>
<section id="image" class="button">
<button type="button">Add photo</button>
<input type="file" accept="image/*" />
</section>
[HTML][1]
'textareaElements' is not plural as you have it here:
var data = textareaElements.value;
This is the correct form:
var data = textareaElement.value;
Here is the link to the site.
The layout of the page consists of a "fixed" sidebar (left), in which buttons are created when a user clicks the "Add" button, accompanied by their chosen title and amount of points the button is worth. Then, when the button is clicked, the button disappears and the points are added on to the "Points" value, which is in the middle "div" of the page.
On the far right there is an empty div, I tried to make the same kind of thing, except I could never get it to work. What I wanted was to create another similar dynamically created button or "span" of some sort, where when the user clicks it, the points allocated to said button/span are the deducted from the total number of points. I was thinking of it as a redeeming system if that makes sense. Using coins, which I would just assign to be half the number of points.
Also, I was able to simply store the number of points and the level in localStorage, but I wasn't sure how to store the created buttons, so they disappear after every refresh, and I can't figure out how to do it, since they're not specifically coded in?
Also, if possible, how would I go about a notification div that creates an alert for each button that is clicked. The alert would say something along the lines of "You have completed task name", and it would store it in localStorage, so the user can see the buttons that were clicked in notification form.
One more thing, upon creating the button, there is a title and a number of points the user has to assign, under the second input text box, there are 5 different coloured "spans", each representing a different "field" you might say, in this case it's different subject, how would I make it so that when the user clicks one of the "Spans", the button created will be the same colour as the span they clicked?
I know I'm asking for a lot, but I have tried to do all of which I've asked for and have had massive troubles. If anyone thinks they can help me out It would be greatly appreciated. Thank you in advance.
Here is the code, html and javascript. The CSS is bootstrap.
HTML
<div >
<div id='header'>
<h2 style='font-size:71px'>Reward System</h2>
<div>
<ol class="breadcrumb" style="width:58%">
<li class="active">
<center> Home
</li>
<li>
About
</li>
<li>
Refresh </center>
</li>
</ol>
</div></div><center>
<div id='main'>
<div id='rightSide' class='well'>
</div>
<div class='well' id="addc" style='width:520px'>
<div id="addc">
<input class='form-control' maxlength="15" id="btnName" placeholder="New Task"
style='width:480px' type="text"><br>
<input maxlength="3" class='form-control' id="btnPoints" placeholder="Points"
style='width:480px' type="text"><br>
<span class="label label-danger">Mathematics EX1</span>
<span class="label label-primary">Mathematics EX2</span>
<span class="label label-success">Physics</span>
<span class="label label-info">Chemistry</span>
<span class=
"label label-warning">English Advanced</span><br>
<br>
<button id="addBtn" >Add</button>
</div>
</div>
<div class='panel panel-default' style='width:520px;height:100px'>
<h3><Strike>z</strike> Points</span></h3>
<div class='badge' id="result">
0
</div>
</div>
<hr style="width:520px;">
<div class='panel panel-default' style="width:520px;">
<h3>Level</h3>
<p class='badge' style='width:50px' id='lvl'>0</p>
<div class="progress" style='width:300px'>
<div class="progress-bar progress-bar-success" id='perce'
style="width;"></div>
</div>
</div><br>
</div>
<div id='leftSide' class='well'>
<center> <h3> Tasks </h3> </center>
<div class='well' id="container" style='width:260px;height:85%'>
</div>
<div id='reset'>
<button class='btn btn-warning' onclick='clearme()'>Reset</button>
</center>
</div>
</div>
JavaScript
var resDiv = document.getElementById('result');
resDiv.innerText = localStorage.getItem('myResult');
var levelDiv = document.getElementById('lvl');
levelDiv.textContent = localStorage.getItem('myLevel');
var btns = document.querySelectorAll('.btn');
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
}
var addBtn = document.getElementById('addBtn');
addBtn.className = "btn btn-default";
addBtn.addEventListener('click', function() {
var container = document.getElementById('container');
var objDiv = document.getElementById("container");
objDiv.scrollTop = objDiv.scrollHeight;
var btnName = document.getElementById('btnName').value;
var btnPoints = parseInt(document.getElementById('btnPoints').value);
if (!btnName)
btnName = "Button ?";
if (!btnPoints)
btnPoints = 50;
var newBtn = document.createElement('button');
var newPnt = document.createElement('span');
newBtn.className = 'btn btn-info';
newBtn.innerText = btnName;
newBtn.setAttribute('data-points', btnPoints);
newBtn.addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
newPnt.className = 'label label-default';
newPnt.innerText = "+" + btnPoints;
container.appendChild(newBtn);
container.appendChild(newPnt);
});
function addToResult(pts) {
// NaN is falsy, so you can just use || to make a fall-back to 0
var result = parseInt(resDiv.innerText, 10) || 0,
lvl = 0,
a = 100;
result = result + parseInt(pts, 10) || 0;
var pen = (result/500)*100;
while (result > (5 * a)) {
lvl += 1;
a += 100;
pen -= 100;
}
document.getElementById('perce').style.width = pen +"%";
resDiv.innerText = result;
levelDiv.innerText = lvl;
localStorage.setItem("myResult", result);
localStorage.setItem("myLevel", levelDiv.textContent);
}
function clearme() {
localStorage.clear();
}
To keep your buttons in localStorage you will need to create your own object that holds the button's name and points, then use JSON.stringify to turn an array of these objects into a string. That string can then be used with localStorage.setItem
function MyButtonObject(name,points){
this.name=name;
this.points=points;
}
var list=[new MyButtonObject('example',100)];
localStorage.setItem( 'btnList' , JSON.stringify(list) );
Next I would procede by seperating the code that makes a new buttons into its own function so it can be called when the page loads and you want to rebuild your button elements.
var listJSON=localStorage.setItem( 'btnList' );
var list= listJSON?JSON.parse(listJSON ):[];
list.forEach(function(btn){
makeButtonElements(btn);
});
function makeButtonElements(btn){
var btnName=btn.name, btnPoints=btn.points;
var newBtn = document.createElement('button');
var newPnt = document.createElement('span');
....etc....
Your existing function that creates buttons would call this one as well as creating a new MyButtonObject adding it to the array of said objects and storing that array with localStorage.setItem. The function that removes buttons will need updating to remove the correct object from the array and calling localStorage.setItem as well as adding your planned notification messages (and storing them).
You should probably take some time to plan what other features you might want (such as deleting buttons without scoring their points, displaying notifications etc) and think about how you can break those processes down into functions that can be reused at different points in your program (eg new button/notification created, existing button/notification loaded from storage)
Here is a handy function that copies a style property from one element to another that should help you set the buttons colours the way you want.
function copyStyle(prop,fromEl,toEl){
toEl.style[prop]=window.getComputedStyle(fromEl)[prop];
}
Note: I haven't check or tested any of this code so make sure you read through it and understand what it is meant to do before you start copying and pasting into your own program.
i have an input which displays data in local storage underneath. At the moment it currently keeps adding whatever has been inputted and displays with an '' in between. This is fine however all I need is for it to Store and display ONE input and display it. If the user
wants to change the input, there will be a button which clears local storage.
Can anybody help with the function for this.
<script>
function storeText(inputID) {
//check to see if the localStorage item already exists
var userInput = localStorage.userInfo;
//set it up for new data to be appended
if(userInput!=null) userInput+=" ";
else userInput="";
//add the new data
userInput += document.getElementById(inputID).value;
//set the localStorage field with the updated data
localStorage.userInfo = userInput;
//write it to the page
document.getElementById("result").innerHTML = localStorage.userInfo;
if (userInput > 1){
alert("Please Clear to add a new goal");
return false;
}
</script>
This is my Input and display
<input id="userText" type="text"/>
<input type="button" value="store" onclick="storeText('userText')"/>
<div id="result">
Result here
</div>
localStorage.clear(); - this will clear local storage entirely
localStorage.removeItem('userInput'); - this removes a specific item - you can then just re-add it.
Just apply this to your buttons onClick event