How to create local storage? - javascript

My website has tabs and within that tab, info cards and a checkbox on the right hand side that highlights the card in a different colour. How can I makes it so that onclick the highlighting is saved even if the page is refreshed or if the page is sent as a link? Full code here: http://codepen.io/johnsonshara/pen/obGjGN (below code not in code pen version)
What I have tried:
function save () {
var fieldValue = document.getElementById('like').value;
localStorage.setItem('checkbox', 'fieldValue');
}
function load () {
var storedValue = localStorage.getItem('checkbox');
if(storedValue){
document.getElementById('like').value = storedValue;
}
}
And This:
function save() {
if(typeof(Storage) !== "undefined") {
if (localStorage.setItem) {
localStorage.setItem = document.getElementById("like");
} else {
localStorage.getItem = .hasClass.apply;
}
document.getElementById("like").innerHTML = localStorage.toString;
} else {
document.getElementById("like").innerHTML = "Sorry, an error occured.";
}
}
html
<input type="checkbox" class="faChkRnd" onclick="save()" id="like" >

Check out the following link to see how you can use the local storage:
http://www.w3schools.com/html/html5_webstorage.asp
Quick example code of how it would work:
// Put the object into storage
localStorage.setItem('testObject', "testing");
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
Example using your example code above:
alert(load());
$(document).on("click", "#clickME", function(){
save();
});
function save ()
{
var fieldValue = "testString";
localStorage.setItem('checkbox', fieldValue);
}
function load ()
{
var storedValue = localStorage.getItem('checkbox');
if(storedValue)
{
console.log("VALUE :" + localStorage.getItem('checkbox'));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="clickME">Click me</button>

or if the page is sent as a link
You should store your data as a url parameter not in the local storage. So anyone that click on the link will get the data.
See this link to know more about using url parameters with JS:
How to get the value from the GET parameters?

Related

Inserting a Link of a Picture That Had been Added to Google Drive into a Google Sheet

This is a second part to the problem that had been resolved here: Insert Image Link from Google Drive into Google Sheets After Uploading an Image via Web App
I'm developing a web application where a user can upload a picture by clicking on a button. This action will upload pictures into a certain directory in my google drive with a unique folder and name.
Now, I'm trying to copy and paste the google drive link of a picture any time it has been uploaded.
With the help of #Tanaike, I was able to get the link of the url from google drive into the google sheet when I pre-assign a part of the folder name (fn) and the picture title (i) within the getFileUrl(fn,i) function in "Code.gs". But I get this "TypeError: Cannot call method "getFilesByName" of undefined." output whenever I try to pass the user-input "fn" and "i".
page.html
--This is the front end, where a user uploads the picture
<html>
<head>
<body>
<form action="#" method="post" enctype="multipart/form-data">
<div class="row">
<div class="file-field input-field">
<div class="waves-effect waves-light btn-small">
<i class="material-icons right">insert_photo</i>
<span>Import Picture</span>
<input id="files" type="file" name="image">
</div>
<div class="file-path-wrapper">
<input disabled selected type="text" class="file-path
validate" placeholder="Choose an image">
</div>
</div>
</div>
</form>
<?!= include("page-js"); ?>
</div> <!-- CLOSE CONTAINER-->
</body>
</html>
This is part of the javascript to put relevant info in an array, which will later be used to append a row in the google sheet
page-js.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="https://gumroad.com/js/gumroad.js"></script>
document.getElementById("files").addEventListener("loadend",doStuff1);
document.getElementById("addAnother").addEventListener("click",doStuff1);
<script>
function doStuff1(){
num.picNum2=i;
var personName=document.getElementById("fn").value;
google.script.run.withSuccessHandler(doStuff2).getFileUrl("fn","i"); // Modified by Tanaike
var userInfo ={};
userInfo.firstName= document.getElementById("fn").value;
userInfo.number=i;
userInfo.fileUrl=fileId00;
num.picNum=i;
i++;
google.script.run.userClicked(userInfo);
}
// Added by Tanaike
function doStuff2(fileId00) {
var userInfo = {};
userInfo.firstName = document.getElementById("fn").value;
userInfo.number = i;
userInfo.fileUrl = "https://docs.google.com/document/d/"+fileId00 +"/";
i++;
google.script.run.userClicked(userInfo);
}
</script>
This is part of the javascript to upload picture file into the Google drive
(still part of page-js.html)
var file,
reader = new FileReader();
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'- '+today.getDate();
reader.onloadend = function(e) {
if (e.target.error != null) {
showError("File " + file.name + " could not be read.");
return;
} else {
google.script.run
.withSuccessHandler(showSuccess)
.uploadFileToGoogleDrive(e.target.result,num.picNum,date,$('input#fn')
.val(),$('input#date').val());
}
};
function showSuccess(e) {
if (e === "OK") {
$('#forminner').hide();
$('#success').show();
} else {
showError(e);
}
}
function submitForm() {
var files = $('#files')[0].files;
if (files.length === 0) {
showError("Please select a image to upload");
return;
}
file = files[0];
if (file.size > 1024 * 1024 * 5) {
showError("The file size should be < 5 MB.");
return;
}
showMessage("Uploading file..");
reader.readAsDataURL(file);
}
function showError(e) {
$('#progress').addClass('red-text').html(e);
}
function showMessage(e) {
$('#progress').removeClass('red-text').html(e);
}
</script>
This part grabs the array "userInfo" and appends the content in a row within a designated google sheet. Any time, I click on the button in the front end, it creates a new row.
This is where if I set fn and i values within the getFileUrl function manually and have a correponding picture and a folder under the designated directory, I get a valid link back in my google sheet. However, if I leave the argument as variables that the user input in the web app, I get the aforementioned error in my link within the sheet.
Code.gs
//google sheet web script
var url="https://docs.google.com/spreadsheets/d/XXXXX";
function getFileUrl(fn,i){
try{
var today0 = new Date();
var date0 = today0.getFullYear()+'-'+(today0.getMonth()+1)+'-'
+today0.getDate();
var dropbox0 = "OE Audit Pictures";
var folder0,folders0 = DriveApp.getFoldersByName(dropbox0);
while (folders0.hasNext())
var folder0=folders0.next();
var dropbox20=[date0,fn].join(" ");
var folder20,folders20=folder0.getFoldersByName(dropbox20);
while (folders20.hasNext())
var folder20=folders20.next();
var file0, files0= folder20.getFilesByName(i);
while (files0.hasNext())
var file0=files0.next();
var fileId0=file0.getUrl();
return fileId0;
} catch(f){
return f.toString();
}
}
function userClicked(userInfo){
var ss= SpreadsheetApp.openByUrl(url);
var ws=ss.getSheetByName("Data");
ws.appendRow([userInfo.number,new Date(),
userInfo.firstName,userInfo.fileUrl]);
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function uploadFileToGoogleDrive(data, file, fn, date) {
try {
var dropbox = "OE Audit Pictures";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var contentType = data.substring(5,data.indexOf(';')),
bytes =
Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),
blob=Utilities.newBlob(bytes, contentType, file)
var dropbox2=[fn,date].join(" ");
var folder2, folders2=folder.getFoldersByName(dropbox2)
if (folders2.hasNext()){
folder2=folders2.next().createFile(blob);
} else {
file = folder.createFolder([fn,date].join(" ")).createFile(blob);
}
return "OK";
} catch (f) {
return f.toString();
}
}
As #Jescanellas and #Tanaike commented, the better approach is to fix your code editing the function doStuff2 in page-js.html as this:
function doStuff2(fileId00) {
var userInfo = {};
userInfo.firstName = document.getElementById("fn").value;
userInfo.number = i;
userInfo.fileUrl = "https://docs.google.com/document/d/"+fileId00 +"/";
i++;
google.script.run.userClicked(userInfo);
}
About the error you're getting, you're not using the brackets in the whiles, this is causing the errors because only takes the first line after the while inside the loop. Code.gs:
while (folders0.hasNext()) {
var folder0=folders0.next();
var dropbox20=[date0,fn].join(" ");
var folder20,folders20=folder0.getFoldersByName(dropbox20);
while (folders20.hasNext()) {
var folder20=folders20.next();
var file0, files0= folder20.getFilesByName(i);
while (files0.hasNext()) {
var file0=files0.next();
var fileId0=file0.getUrl();
return fileId0;
}
}
}
Regarding your question about the file Id, you can get it easily after you create the file, because this will return you a File object from which you can get the ID using the getId method [1]:
file = folder.createFolder([fn,date].join(" ")).createFile(blob);
fileId = file.getId();
[1] https://developers.google.com/apps-script/reference/drive/file

i need to store the value in angularjs function

im having ng-change function in the name of myFunc() to store the response from html listitem.
the respose value is getting saved in the local variable of the function but when i refresh the controller or page the values are deleted. i need to store the value during ng-change in myFunc() after multiple page or controller refersh the value will be stored in the controller variable to do the further logics
on page onload
myhtml code
<div class="col-sm-4">
<ol name="ManualFiles" title="Select" required validType="select" ng-
change="myFunc()" ng-model="data.manualsFiles" ng-selected="
{{data.manualsFiles}}">
<li nya-bs-option="type in manualsFiles" data-value="type.key">
<a> {{type.val}} </a>
</li>
</ol>
</div>
mycontroller code
$scope.myFunc = function() {
var manualFile=$scope.data.manualsFiles;
var cdSoftwares=$scope.data.cdSoftware;
var price=$scope.data.priceBook;
var referenceBooks=$scope.data.referenceBook;
var vpnAccounts=$scope.data.vpnAccount;
if((manualFile && cdSoftwares && price && referenceBooks && vpnAccounts)!==0)
{
$scope.isTypeDisabled=false;
}
else
{
$scope.isTypeDisabled=true;
$scope.data.status="Pending";
}
};
Try it using sessionStorage. In that way, you would not lose your values at least the user closes the window.
Now, the idea is, in the function myFunc,
$scope.myFunc = function() {
var manualFile=$scope.data.manualsFiles;
var cdSoftwares=$scope.data.cdSoftware;
var price=$scope.data.priceBook;
var referenceBooks=$scope.data.referenceBook;
var vpnAccounts=$scope.data.vpnAccount;
//Here, use sessionStorage to save your values in the browser.
var data = {'manualFile': manualFile, 'cdSoftwares': cdSoftwares, 'price': price, 'referenceBooks': referenceBooks, 'vpnAccounts': vpnAccounts}
sessionStorage.setItem('yourNameKey', data);
if((manualFile && cdSoftwares && price && referenceBooks && vpnAccounts)!==0)
{
$scope.isTypeDisabled=false;
}
else
{
$scope.isTypeDisabled=true;
$scope.data.status="Pending";
}
};
Then, when Users are refreshing the site, you would create a function just for recover that values in your variables. You'd use destructuring assignment to recover your values.
function recoverValues() {
var data = sessionStorage.getItem('yourNameKey');
var { manualFile, cdSoftwares, price, referenceBooks, vpnAccounts } = data;
}
recoverValues();
You can use sessionStorage property of $window.
Note: The data stored using sessionStorage will be available only in that session. (data will get deleted when the browser tab is closed)
You can achieve your requirement using this example. Try this demo
<script type="text/javascript">
var app = angular.module('MyApp', ["ngStorage"])
app.controller('MyController', function ($scope, $localStorage, $sessionStorage, $window) {
$scope.Save = function () {
$localStorage.LocalMessage = "LocalStorage: My name is Pet Jones.";
$sessionStorage.SessionMessage = "SessionStorage: My name isPet Jones.";
OR
$sessionStorage.setItem("status", "pending");
}
$scope.Get = function () {
$window.alert($localStorage.LocalMessage + "\n" + $sessionStorage.SessionMessage);
OR
console.log($sessionStorage.getItem("status"))
}
});
</script>

Javascript plugin needs to call back to client's Javascript

I am working on a plugin that allows to add an item to the shopping cart. The plugin is mine, and the shopping cart belongs to the customer. The idea is to add my plugin with a few lines of code to configure.
Once an item is bought, I need to call a function on the customer page so it can be added to the cart, but I didn't manage.
I have this code:
<script type="text/javascript">
$(document).ready(function () {
//plugin1.CallBackTest;
});
var plugin1 = new function() {
this.CallBackTest = function (str) {
console.log("callback in class");
FunctionIWantToCall(str);
}
}
function FunctionIWantToCall(str) {
console.log("callback on client " + str);
}
</script>
<div class="htmlcreatedbyplugin">
<button onclick="CallBackTest('something')">send back</button>
</div>
if I change this line to
send back
it will work, but this html is generated through the plugin class, and I don't know how to retrieve the name of the variable.
The customer should be able to tell the plugin which function to call, e.g
plugin1.AddToCartFunction = FunctionIWantToCall;
Any ideas?
Thank you Stavros Angelis, it works:
<script type="text/javascript">
$(document).ready(function () {
plugin1.CallBackFunction = "FunctionIWantToCall";
});
var plugin1 = new function () {
var myplugin = this;
this.CallBackFunction = "";
this.CallBackTest = function () {
console.log("callback in class");
var item = JSON.parse($(this).attr("vals"));
if (myplugin.CallBackFunction != "") {
window[myplugin.CallBackFunction](item);
}
}
function BindCartButtons() {
console.log("binding buttons")
$(document).on("click", ".htmlcreatedbyplugin > button", myplugin.CallBackTest);
}
BindCartButtons();
}
function FunctionIWantToCall(item) {
console.log("callback on client " + item.id);
}
</script>
<div class="htmlcreatedbyplugin">
<button type="button" vals="{"id":12345, "color":"blue"}">Buy Me</button>
</div>

add values to textbox history without submitting the form using javascript or Jquery

Hello friends I have a <input type="text" id="tempID" /> element in my form
I also have an <input type="button" onclick="doSomething()" /> element in my form.
I want to add the text box value to textbox history when user clicks on the button.
I am processing the request using Jquery ajax. So I have to do it with javascript or Jquery.
Is this possible to add values to the history of particular <input type="text" /> element using javascript/Jquery..??
Here is how you can do it using HTML5 LocalStorage
$( "#tempID" ).autocomplete({
source: function( req, resp ) {
var temp = localStorage.getItem('custom_history');
var data = JSON.parse(temp);
resp( data );
}
});
$('#tempID').on('blur', function() {
var temp = localStorage.getItem('custom_history');
var data = JSON.parse(temp);
if($.trim(this.value).length > 0)
data.push(this.value);
localStorage.setItem('custom_history', JSON.stringify(data));
});
What I am doing is Setting the value into HTML5 Local storage when users moves away from the input field, clicks somewhere else.
Then retrieving that and setting that as source for jQuery UI auto complete.
Here is a working fiddle http://jsfiddle.net/joycse06/EBduF/173/
Enter some value. Click somewhere else. Click back again and add other values. The refresh the fiddle and start typing one of those and auto complete will show up.
UPDATE
Based on his comments and later chat the final code he need is this, I am pasting in if it might someone else later
// if we dont set this line then ff will return null, and null.length will throw an error
if(!localStorage.getItem('custom_history'))
localStorage.setItem('custom_history','');
$( "#test" ).autocomplete({
source: function( req, resp ) {
var term = req.term;
var temp = localStorage.getItem('custom_history');
var data = [];
if(temp.length > 0)
data = JSON.parse(temp);
var intRegex = /^\d+$/;
data = $.map(data,function(val){
if(intRegex.test(val)){
if(val.indexOf(term) != -1)
return val;
else
return null;
}
else
return null;
});
resp( data );
}
});
$('#save').on('click', function() {
var temp = localStorage.getItem('custom_history');
var data = [];
if(temp.length > 0)
data = JSON.parse(temp);
var value = $.trim($('#test').val());
if(value.length > 0){
if($.inArray(value,data) != -1){
//alert('Duplicate');
return;
}
}
data.push(value);
localStorage.setItem('custom_history', JSON.stringify(data)); // set item to localStorage
});
You can use localStorage like following:
var arr = [];
$('input#tempID').on('click', function() {
arr.push(this.value);
localStorage.setItem('history', JSON.stringify(arr)); // set item to localStorage
});
To retrieve that value try,
var temp = localStorage.getItem('history');
if(retarr) { // checking that data it stored in localStorage or not, if not exists temp = null
var allHistories = JSON.parse(temp); // now you have history
console.log(allHistories);
}
I think you need something like autocomplete

How can I delete the selected messages (with checkboxes) in jQuery?

I'm making a messaging system and it has a lot of AJAX. I'm trying to add a bulk actions feature with check boxes. I've added the checkboxes, but my problem is that I don't know how to make something happen to the selected messages.
Here's my function that happens whenever a checkbox is clicked:
function checkIt(id) {
if ($('#checkbox_' + id).is(':checked')) {
$('#' + id).addClass("selected");
}
else {
$('#' + id).removeClass("selected");
}
}
But, I don't know where to go from there.
Here is some example markup for one of the lines [generated by PHP] of the list of messages:
<div class="line" id="33" >
<span class="inbox_check_holder">
<input type="checkbox" name="checkbox_33" onclick="checkIt(33)" id="checkbox_33" class="inbox_check" />
<span class="star_clicker" id="star_33" onclick="addStar(33)" title="Not starred">
<img id="starimg_33" class="not_starred" src="images/blank.gif">
</span>
</span>
<div class="line_inner" style="display: inline-block;" onclick="readMessage(33, 'Test')">
<span class="inbox_from">Nathan</span>
<span class="inbox_subject" id="subject_33">Test</span>
<span class="inbox_time" id="time_33" title="">[Time sent]</span>
</div>
</div>
As you can see, each line has the id attribute set to the actual message ID.
In my function above you can see how I check it. But, now what I need to do is when the "Delete" button is clicked, send an AJAX request to delete all of the selected messages.
Here is what I currently have for the delete button:
$('#delete').click(function() {
if($('.inbox_check').is(':checked')) {
}
else {
alertBox('No messages selected.'); //this is a custom function
}
});
I will also be making bulk Mark as Read, Mark as Unread, Remove Star, and Add Star buttons so once I know how to make this bulk Delete work, I can use that same method to do these other things.
And for the PHP part, how would I delete all them that get sent in the AJAX request with a mysql_query? I know it would have to have something to do with an array, but I just don't know the code to do this.
Thanks in advance!
How about this
$('#delete').click(function() {
var checked = $('.inbox_check:checked');
var ids = checked.map(function() {
return this.value; // why not store the message id in the value?
}).get().join(",");
if (ids) {
$.post(deleteUrl, {idsToDelete:ids}, function() {
checked.closest(".line").remove();
});
}
else {
alertBox('No messages selected.'); // this is a custom function
}
});
Edit: Just as a side comment, you don't need to be generating those incremental ids. You can eliminate a lot of that string parsing and leverage jQuery instead. First, store the message id in the value of the checkbox. Then, in any click handler for a given line:
var line = $(this).closest(".line"); // the current line
var isSelected = line.has(":checked"); // true if the checkbox is checked
var msgId = line.find(":checkbox").val(); // the message id
var starImg = line.find(".star_clicker img"); // the star image
Assuming each checkbox has a parent div or td:
function removeDatabaseEntry(reference_id)
{
var result = null;
var scriptUrl = './databaseDelete.php';
$.ajax({
url: scriptUrl,
type: 'post',
async: false,
data: {id: reference_id},
success: function(response)
{
result = response;
}
)};
return result;
}
$('.inbox_check').each(function(){
if ($(this).is(':checked')){
var row = $(this).parent().parent();
var id = row.attr('id');
if (id == null)
{
alert('My selector needs updating');
return false;
}
var debug = 'Deleting ' + id + ' now...';
if (console) console.log(debug);
else alert(debug);
row.remove();
var response = removeDatabaseEntry(id);
// Tell the user something happened
$('#response_div').html(response);
}
});

Categories

Resources