limiting local storage input to 1 - javascript

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

Related

How to add more data into LocalStorage instead of overwriting it in contenteditable attribute?

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 to get data from Local storage onClick in javascript

How to use the data from local storage in javascript onClick. I have my html file and javascript file below. Thanks
<fieldset>
<form>
<!--GET USER NAME-->
<p>
<label for="inName" >What is your name?</label>
<input type="text" id="inName" name="f_name"/>
</p>
<!-- GET COLOUR--> // I m not sure about how the get color as user can
//choose the color from drop down color palet.
<p>
<label for="inColor" >What is your favourite colour? </label>
<input type="color" id="inColor" name="f_color" />
</p>
<p> // how to get the value when user clicks the button
// in order to call onClick function to output the
user's name and
// display favorite color in background.
<input type="submit" value="Click to save" />
<p/>
</fieldset>
</form>
I don't know how to get data from local storage when user click to submit the form :
//NOW THAT WE HAVE STORED DATA ON ONE PAGE, WE CAN ACCESS IT FROM ANY PAGE ON THIS
WEBSITE.
window.onload = function(){
//GET ELEMENTS USED FOR OUTPUT
var userOut = document.getElementById("newMsgBox");
//GET VALUES FROM COOKIES/LOCAL STORAGE
var userName = localStorage.getItem("nameIn");
var userColor = localStorage.getItem("inColor");
//CREATE OUTPUT WITH VALUES
if (userName !== null) {
userOut.innerHTML = " " +userName;
}
}//end onload
If you want to listener event from an specific button and then access to your localStorage you could do this:
first get the element:
const button = document.getElementById('<clickable_element_id>');
then add a listener to the button;
button.addEventListener("click",(event)=> {
event.preventDefault() // only if you want to prevent the action
//here you can access to your local store items like:
const a = localStorage.getItem("<item you saved previously>");
...
});
It's really unclear what you want to do but
let inColor = document.getElementById('inColor');
let inName = document.getElementById('inColor');
Will fetch the values for you.
I think you are looking for something like this.
<script>
function saveData() {
let inColor = document.getElementById('inColor');
let inName = document.getElementById('inName');
localStorage.setItem("inColor", inColor);
localStorage.setItem("inName", inName);
}
</script>
<input type="Button" value="Click to save" onclick="saveData"/>
Import Jquery and use this. I hope help you. when you click on button with id idOfBtn jquery gonna eject the event and call the localStorage with key (key). Replace it for you key name.
$("#idOfBtn").click(function() {
alert(localStorage.getItem('_key_'));
});

javascript & html - creating new checkbox option everytime user enters item in textbox

So basically I'm creating a program that allows the user to create and manage a ‘to-do list’. This will allow the user to add new items, remove selected items, highlight/un-highlight selected items, and sort the items, etc. I'm currently working on the add button, but I'm extremely confused with different functions in HTML and code that will allow me to manipulate the DOM.
When the user clicks the add button and the item name is valid, a new item should be added to the page’s to-do list (which esentially creates a new checkbox for every item the user adds). The checkbox is basically so the item can be selected/deselected, as well as the text that was in the item name textbox when the add button was clicked.
I guess I have two problems right now. I'm trying to verify that the item name is at least 1 character long. I wrote code in my "addHandler.js" file but when I write nothing in the textbox and click on the add button on my HTML browser, no error message pops up. I don't know why it's ignoring my function. Another thing I'm struggling with is the part that creates a new checkbox for every valid item that is added. I know how to create a checkbox on my HTML page, but I don't understand how to get my program to create a new one per item that the user inputs.
Any help or push in the right direction would be appreciated. I'm also new to HTML and javascript, so explaining stuff in simple terms would also make me really grateful.
todo.html code:
<html>
<head>
<title>Checklist</title>
</head>
<body>
<div><h1>My to-do list</h1></div><br />
<div id ="myCheckList">Enter an item:</div>
<div>Type something: <input type="text" id="textbox"></input></div>
<button type="button" id="addBut">Add item</button>
<button type="button" id="removeBut">Remove items</button>
<button type="button" id="toggleBut">Toggle highlight</button>
<button type="button" id="sortBut">Sort items</button>
<script src="addHandler.js"></script>
</body>
</html>
addHandler.js code:
function init(){
let button = document.getElementById("addBut");
button.onclick = buttonClicked;
let tb = document.getElementById("textbox");
tb.onblur = validate;
}
function add(){
let someEle = document.getElementById("myCheckList");
someEle.innerHTML = 'You added an item';
}
function validate(){
if(document.getElementById("textbox").value.length == 0){
alert("You need to enter something");
}
}
You should have a wrapper that contains your checkbox items that you can append new elements to.
<div id="checklist_items"></div>
Then you can use the following function to create a new div that contains a checkbox and the entered text, and then append it to your checklist:
function addItem() {
var input = document.getElementById("textbox");
var wrapper = document.getElementById("checklist_items");
if(input.value.trim() != "") {
var new_element = document.createElement("DIV");
new_element.innerHTML = '<input type="checkbox"> '+input.value;
wrapper.appendChild(new_element);
}
else {
alert("You must enter at least 1 character.");
}
}
I would also use the following to add the function to your button:
document.getElementById("addBut").addEventListener("click", addItem);

Progress bar indicating form completion in jQuery

I'm working on a progress bar using the progress element that increases as the user completes fields in a lengthy form. I found this SO thread which was helpful in getting some baseline functionality using a data-* attribute, but my form has a "Save Progress" feature that will save any entered field information to the browser's local storage to be retrieved later. Thus, in the event that a user returns to the form with saved data, I'd like the bar to reflect that level of progress.
Here's what is working thus far- sample markup using the data-attribute data-prog for a form field:
<!-- FORM - SAMPLE FIELD -->
<div id="form">
<div class="field-group required">
<label for="mgd_org_name">Organization Name:</label>
<div>
<input id="mgd_org_name" type="text" name="mgd_org_name" placeholder="Please enter your organization's name" required data-prog="6">
</div>
</div>
</form>
<!-- Progress bar -->
<div id="form-progress">
<p>Form Progress</p>
<progress max="100" value="0" id="progress"></progress>
</div>
And the jQuery thus far:
$(function() {
// get all form inputs w/ data-prog values
var inputs = $('#dossier-form').find('input[data-prog], textarea[data-prog]');
var progBar = $('#progress');
var progVal = 0;
$(inputs).change(function() {
if ($(this).val().length > 0) {
progVal += $(this).data('prog');
progBar.attr('value', progVal);
}
});
});
In this way, each field has a data-prog value that will be added to the progVal and reflected in the progress bar level. What I'm having trouble with is loading an initial value for any form fields that might already be filled on load—thus, I would need to find all fields that have a value entered, add the associated data-prog values, and initially load that value into the progress bar. I would also like to accordingly decrease the progress value in the event that a field is cleared.
For the initial load, I've been trying something like the following (not working):
var inputsSaved = $(inputs).val();
if($(inputsSaved).length > 0) {
progVal = $(inputs).data('prog');
console.log('has existing progress');
} else {
progVal = 0;
console.log('does not have existing progress');
}
I'm not quite sure how to find the fields with text entered on load and grab the associated prog values nor how to decrease the value accordingly if a field is cleared. Any assistance here is greatly appreciated!
First, your inputs selector can be replaced by:
var inputs = $('#dossier-form [data-prog]');
Then, $(inputs).change(..., inputs already is a jQuery object. No need to wrap it with $().
You had the progress update function correct. I just placed it in a named function to be able to call it from different places in code (and avoid duplicate code).
I added the localStorage save and retreive...
$(function() {
// get all form inputs w/ data-prog values
var inputs = $('#dossier-form [data-prog]');
var progBar = $('#progress');
var progVal = 0;
// Establish the "dificulty unit" base.
var totalDifficulty = 0;
inputs.each(function(){
totalDifficulty += $(this).data('prog');
});
var difficultyUnit = 100/totalDifficulty;
// Update progressbar
function updateProgress(el){
progVal += parseFloat($(el).data('prog')) * difficultyUnit;
progBar.val(progVal);
}
// LocalStorage on load
inputs.each(function(){
var value = localStorage.getItem(this.id);
if(value !=null && value !=""){
$(this).val(value);
updateProgress(this);
}
}); // End load from LocalStorage
// Blur handler to save user inputs
inputs.on("blur",function(){
// Reset the progress
progVal = 0;
progBar.val(progVal);
// Loop through all inputs for progress
inputs.each(function(){
if ($(this).val().length > 0) {
updateProgress(this);
}
// LocalStorage
localStorage.setItem(this.id,this.value);
});
}); // End on blur
}); // End ready
localStorage isn't allowed in the SO snippets... So have a look at this CodePen.
So you can now give some "difficulty level" without worring about the total obtained by all the data-prog to be 100. Just give an arbitrary number you feel like. ;)
If you always add up the progress from scratch, you can do the same thing in both cases.
$(function() {
// get all form inputs w/ data-prog values
var inputs = $('#dossier-form').find('input[data-prog], textarea[data-prog]');
var progBar = $('#progress');
function update () {
var progVal = 0;
inputs.each( function () {
if ($(this).val().length > 0) {
progVal += Number( $(this).data('prog') );
}
})
progBar.attr('value', progVal);
}
inputs.change( update );
// Fill in fields from localStorage, then:
update();
});

How to check if a page comes after clicking the back button using jQuery?

I have a form where I am calculating the total amount using jQuery.
The function I created for that is updateTotal();
and the form action is another page and the action page has this button:
<button class="btn btn-success" onclick="history.go(-1);" type="submit" name="edit">EDIT</button>
so when the user clicks on the EDIT button page goes back to the form again (first page) and all the filled up details are there except the repetitve fields created using jQuery.
The sample form is here in js fiddle
I just want to run this function updateTotal(); if the user comes to the form by clicking the EDIT (basically browse go back) button..
Is there any way to do this in jQuery?
UPDATES FOR FUTURE REFERENCE - I SOLVED IT LIKE THIS
html:
<input type="text" id="amount" name="amount[]" placeholder="Amount" required="required" class="form-control inputChangeVal reqF reqFamount" data-js-input-type="number" />
and the jQuery :
jQuery(document).ready(function() {
var hiddenTot = jQuery('.reqFamount').val() ;
jQuery(".totalAmount").val(hiddenTot);
});
Define a hidden field to store the computed value.
<input type="hidden" id="hiddenTotal" />
Then store the calculated value to the hidden field with Id 'hiddenTotal'.
function updateTotal() {
var price = 0;
$(".inputChangeVal").each(function() {
var t = parseFloat(jQuery(this).val(), 10);
price = price + t;
});
var total = price.toFixed(2);
$(".totalAmount").val(total);
$("#hiddenTotal").val(total);
}
Then when the browse back is triggered the hiddenfield is automatically filled by the browser.
Next check when the document is ready, read the value of hiddenTotal and write to totalAmount.
$(document).ready(function (){
// read value and set value of totalAmount to hiddentotal;
var hiddenTotal = $("#hiddenTotal").val() || 0; //use the hiddenTotal value or if not present set 0 as the default value
$(".totalAmount").val(hiddentotal)
}
Now totalAmount is restored. This even works when you leave the page and return using your browsers history.

Categories

Resources