How to save to local storage - javascript

So I have made a table table elements and functions for the pop up and the form. Appending element on clicking save button also works. However I can't make it work the content to be stored and pulled from local storage in refresh page. I am somehow trying to populate the cell with currently generated ID . Considering the fact that I me new at JavaScript I am totally missing something Can someone give me idea what is that. The Code
/*save to td */
$('#save').click(function () {
localStorage.setItem(clickID, JSON.stringify(clickID));
var theName = $('input[name=name]').val();
var theLastName = $('input[name=lastname]').val();
$('input[name=name]').val("");
$('input[name=lastname]').val("");
var $fullCell = $('<p>' + theName + '' + theLastName + '</p>');
if((theLastName+theLastName).length > 0){
$(callingID).append($fullCell);
$(callingID).css('background-color', 'yellow');
}
});
https://jsfiddle.net/9zcj3ab8/27/

In javascript keys for an object must be strings. You can think of localStorage as a persistent Javascript object. Since you are calling JSON.stringify on clickID I am assuming clickID is a javascript object.
The first argument to setItem must be a string, followed by any valid js type for the second argument (documentation for setItem here: https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem)
If clickID is a string:
Additionally, you are saving to localStorage just clickID and a stringified version of clickID. It seems to me that the intended behavior is to store to localStorage a string called clickID as a key (first argument) with the first name and last name as the value (second argument).
Not sure if that is the wrong jsfiddle but your $('#save').click function is nowhere to be found there.

Related

Is there a way to 'reset' a jQuery function each time it is triggered?

I have an eCommerce website product page for a product with color options.
I'm trying to copy the selected color attribute value and append it to the product title, and I'm using any change to the value of #pa_finish as a trigger, to ensure the title is updated with the current selection.
Here is the code I'm presently using:
$( '#pa_finish' ).change(function(){
var var_name = $('#pa_finish :selected').text();
var original = $('h1.product_title.entry-title').text();
$('h1.product_title.entry-title').html(original + ' ' + var_name);
});
The issue I'm having is that, instead of the title refreshing with each trigger, the var_name variable is being iterated alongside the previous value, so the product title ends up simply increasing in length!
Ideally, the pre-existing text value from var_name is cleared, and replaced with the new selection each time a change is made.
Is there a means by which I can 'reset' the function each time it is triggered? Thank you in advance for any help or insight anyone might be able to provide.
Thank you all for your input - I've realised that, as pointed out in the comments, I hadn't established a baseline value for my title.
I have a working example now:
var title = $('h1.product_title.entry-title').text();
$( '#pa_finish' ).change(function() {
var var_name = $('#pa_finish :selected').text();
$('h1.product_title.entry-title').html(title + ' ' + var_name);
});
I've established a value for the original title in a 'title' variable (outside of the function), so that when the function executes it replaces the HTML of:
$('h1.product_title.entry-title')
...with a combination of the original title and the var_name variable, on each change.
Before, it was simply loading the selector again and again, and tagging on the result of var_name, which is why I saw the repitition.
I hope this can help someone in the future.

Local storage not working issues with for loop

I am using local storage to allow the user to return to a form after it has been submitted and amend with previous values persisting.
I succeeded in using the jQuery Storage Api (for set() and get()) but only by writing out long hand for each form element, not ideal. Instead I wanted to push all the form element ids to an array and loop through the array. First part, pushing to the array, works like a charm but the for loop I used is not working.
I intend to use jQuery .each() function but want to understand why my loop is not working first. Thanks.
(function() {
var selectArray = [];
// Getting select ids
$("select").each(function() {
selectArray.push($(this).attr("id"));
});
// Using Local Storage Api
var storage = $.localStorage;
for (var i = 0; i < selectArray.length; i++){
// Get select element
$("#" + selectArray[i]).val(storage.get(selectArray[i]));
// Set select element
$("#" + selectArray[i]).change(function() {
var selectValue = $("#" + selectArray[i]).val();
storage.set(selectArray[i], selectValue);
});
// Check loop is working
console.log(i + ". " + selectArray[i]);
}
}());
Resources:
jQuery v1.11.0
jQuery Storage API
Just change the change event handler like this, avoid reference to i. variable i is getting dangled here.
$("#" + selectArray[i]).change(function() {
var selectValue = $(this).val();
storage.set($(this).attr('id'), selectValue);
});
This should work.
Example
You are right, inside the change handler function you refer to the loop variable 'i'. When the change handler is actually called, 'i' is dereferenced and always contains the last value: selectArray.length

Window.Open Java Script Variable

I am trying to pass a javascript variable to a new window that opens, however if i add a name of "_self", the variable will not be passed:
This won't work, appointmentId is undefined:
var w = window.open("../calendar/appointment.html","_self");
w.appointmentId = appt.id;
This does work:
var w = window.open("../calendar/appointment.html");
w.appointmentId = appt.id;
How can I pass a variable using the _self name, so a new tab/window is not opened?
The variables I am passing are huge. They would take up the URL limit. Sorry I didn't specify this earlier.
Thanks
An alternative is to pass the variable in the querystring.
To redirect:
window.location = "../calendar/appointment.html?appt_id=" + appt.id
On page load:
<script type="text/javascript">
// http://stackoverflow.com/a/901144/1253312
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
window.appointmentId = getParameterByName('appt_id');
</script>
An alternate way to do this is via window.location. For example:
window.location = "../calendar/appointment.html"; // this will send the user here in the current window
In addition, variables are typically passed from page-to-page via the use of a QueryString (sometimes known as GET variables). These typically appear after a question mark. In your case, you could pass the variable like this:
window.location = "../calendar/appointment.html?appointmentId=" + appt.id;
// ../calendar/appointment.html?appointmentId=113
You could also pass the variable after a hash mark:
window.location = "../calendar/appointment.html#" + appt.id;
// ../calendar/appointment.html#113
If you go with the second option, then you can read the variable via location.hash. If you pass it via the QueryString, then you can extract the variable back out of the URL as shown in this question:
How can I get query string values in JavaScript?
window.open can take 3 parameters
https://developer.mozilla.org/en-US/docs/Web/API/Window.open
The second parameter you are passing is the name of the created window.
This is why you don't have it inside the window.
window.open(strUrl, strWindowName[, strWindowFeatures])
Information about supported features can be found in the given url.
The reason why the code you posted doesn't work is because when you use _self, the old document gets cleaned up before the new document can be loaded. Thus, there is no moment in time when the two can communicate synchroneously.
This answer for a slightly different question, but with the same root cause gives several asynchronous communication approaches:
Options you can use are :
Adding it as a parameter using the hash tag (second.php#tmpstr=aaaaaa
Using cookies (there is a nice jQuery cookie plugin)
Moving your whole page into a iFrame (not recommended) and redirecting only the main frame.
Note that using the hash tag is slightly better than using the query string suggested by the other answers because your variable will not end up on the request to the server.
You can use the browser's session storage.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
Before redirecting:
sessionStorage.setItem("appointmentId", appt.id);
Redirect:
window.location = "../calendar/appointment.html";
When appointment.html loads:
window.appointmentId = sessionStorage.getItem("appointmentId");

Trying to reduce repetition of javascript using a variable

I am trying to reduce the repetition in my code but not having any luck. I reduced the code down to its simplest functionality to try and get it to work.
The idea is to take the last two letters of an id name, as those letters are the same as a previously declared variable and use it to refer to the old variable.
I used the alert to test whether I was getting the right output and the alert window pops up saying "E1". So I am not really sure why it wont work when I try and use it.
E1 = new Audio('audio/E1.ogg');
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
fileName.play();
$('#note' + fileName).addClass('active');
});
The code block works when I use the original variable E1 instead of fileName. I want to use fileName because I am hoping to have this function work for multiple elements on click, instead of having it repeated for each element.
How can I make this work? What am I missing?
Thanks.
fileName is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling the play() method on a string, which of course does not exist (hence you get an error).
Suggestion:
Store your objects in a table:
var files = {
E1: new Audio('audio/E1.ogg')
};
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
files[fileName].play();
$('#note' + fileName).addClass('active');
});
Another suggestion:
Instead of using the ID to hold information about the file, consider using HTML5 data attributes:
<div id="#note" data-filename="E1">Something</div>
Then you can get the name with:
var filename = $('#note').data('filename');
This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.

How can I dynamically construct a document element string using a variable in Javascript?

This is driving me nuts, and I'm sure it's both possible and surely simple to do.
I have a page with a whole bunch of dynamically created forms on it. In one of my functions, I need to access one of those forms, so I pass the name of the form in a variable.
Then I need to access the name of that form using the document tree.
However, when I put in the variable, it assumes the name of the variable is the name of the form.
So this does not work:
function myAwesomeFunction(nameOfForm)
{
var selection = document.nameOfForm.nameOfInput.selectedIndex;
}
So I looked around the net and saw that I need to use bracket notation, but this doesn't work either:
function myAwesomeFunction(nameOfForm)
{
var selection = document[nameOfForm].nameOfInput.selectedIndex;
}
I also tried with some quotation action:
function myAwesomeFunction(nameOfForm)
{
var selection = document['nameOfForm'].nameOfInput.selectedIndex;
}
... but no joy.
So, where am I going wrong?
For bonus points... what if both the name of the form and the name of the particular input were both dynamic? Then what?
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var selection = document[nameOfForm][nameOfInput].selectedIndex;
}
Look them up in the forms object - this won't work since it is an array and not an object.
use document.getElementsByName
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var selection = document.getElementsByName(nameOfForm)[nameOfInput].selectedIndex;
}
or even better, set an id attribuite on the form and use document.getElementById to find the form
Try using document.getElementById(nameOfForm) (if you have the ID on the form as well)...
If you can include a jQuery reference to your page, you can easily do the following (again assuming you have the ID on the form):
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var form = $("form#" + nameOfForm);
var input = $("#" + nameOfInput + ":input");
var selection = $(input).val();
}
function focusElement(formName, elemName) {
var elem = document.forms[formName].elements[elemName];
}
try this
formname is name of the form and elemname is input label name

Categories