saving text in local.storage in javascript - javascript

I'm quite new to coding. My goal is to make a simple "daily planner" page where you can save text in each line. I was trying to do this via local.storage, but I'm not quite sure what I'm doing wrong.
I've tried get vs setitem (which I'm not sure if there's a difference) I tried renaming my elements.
div.text(dailyPlanner[i].hour);
let textbox = $("<textarea>");
textbox.attr("data-hour", dailyPlanner[i].line);
textbox.addClass("col-8 col-md-10 description");
textbox.val(dailyPlanner[i].text);
if (currVal !== null) {
localStorage.setItem(textbox, line);
let textbox = localStorage.setItem(textbox)
}

The key needs to be a string so make the key "textbox" and also, what is the value of currVal? Can you confirm it isn't null?

I see two problems in your setIem call:
You are using an html node as a key (textbox) while you should use a string
You are using line as a value, which is undefined in your present code.
So you can try this instead, or adapt this to your case.
localStorage.setItem(dailyPlanner[i].text, dailyPlanner[i].line);

Related

adding .value stops flow of javascript

I'm in the middle of creating a program in the browser which compares the selections of the user with a list of pre-defined holidays using Objects. I tried to create an object from the selections of the user to use in comparisons and select the most matching holiday, however when I try to select the value (adding .value) it seems to break the flow of Java, and none of the code read afterwards is read.
var climateVar = document.getElementById('climateselect')/.value\;
var accVar = document.getElementById('accomadationselect')/.value\;
var durationVar = document.getElementById('duration')/.value\;
var userInput = new Input(climateVar/.value\, accVar/.value\, durationVar/.value\);
for (var key in userInput) {
var woo = userInput[key];
document.getElementById('someDiv').innerHTML += woo/.value\;
}
without any .value/s, this prints[object HTMLSelectElement]null[object HTMLSelectElement] - (I changed "getElementById" to "querySelector" which simply made it print "nullnullnull")
, but when I try to add .value anywhere, the entire script stops working, and so everything under this will not run. Why on earth would adding .value stop the script from working? Nothing else changed.
Also, I'm a novice at this, this was meant to be a practice project, but I've been stuck on this for about a day now. any other advice you might feel like giving would also be appreciated
everywhere I typed /.value\ I've tried to add .value, and it has had the effect of stopping the code
Are you sure you are calling value on a valid object? The object has to exist and support .value to get a result - e.g.
http://jsfiddle.net/pherris/t57ktnLk/
HTML
<input type="text" id="textInput" value="123"/>
<div id="divHoldingInfo">123</div>
JavaScript
alert(document.getElementById('textInput').value);
alert(document.getElementById('divHoldingInfo').innerHTML);
alert(document.getElementById('iDontExist').value); //errors out

proper coding with array.push

I've found some code on a site and been tinkering with it a little. It involves some functions to add and delete students (the add code is below) from an array - into a value field. I can't figure out why in tarnations we need this extra piece of code, however.
Here is the js code:
var students = ['Paulie', 'Nicole', 'Kevin', 'Mare'];
function addClick(){
var addRemove = document.getElementById('addRemoveStudent');
var studentsBox = document.getElementById('studentsBox')
students.push(addRemove.value);
addRemove.value = '';
studentsBox.value = students.join(', ');
}
My question is: Why do we need the addRemove.value = ''; line? I've tested it without that code and it still works fine. Is there a reason we need that?
I can send more code including the HTML but didn't what to overwhelm anyone with the volume.
Thanks so much in advance!
-Anthony
It's not necessary. I guess semantically it means to clear the addRemove box first before replacing the value.
It's optional, but it's simply to clear the text box so the user can enter a brand new value if they want to run the function again.
To clear the value of the addRemoveStudent ( I think it is a input type="text") Just for it, It is not needed in the array. Just to clear the value of that control.
Presumably addRemove is an input element. Setting the value property of an input element to an empty string '' means that the input is emptied: it will have no text in it.
My guess is that this function is run when a button is clicked, so it adds a new student to the array, updates the studentsBox field with the right data, and clears the input element so you can add more if the user wishes to do so.

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 to avoid javascript retrieving values from non-existing elements

Update: clarified question (I hope)
Hi.
I'm developing a plugin in Wordpress and I'm outputting elements according to user privileges A and B.
In case of A, I ouput element "Foo".
In case of B, I output element "Bar".
Up till now, I haven't checked if an element exists before I try to retrieve the value.
This of course gives me a javascript error in some browsers (like IE7).
I've looked at using the typeof() function:
if(typeof(element) == 'undefined') {
//do something...
}
I'm also using jQuery. So one solution could be using this:
if ($("#mydiv").length > 0){
// do something here
}
Using the above methods, makes me having to check each element before trying to retrieve any values.
The "ideal" solution would be to get values based on user privileges. E.g:
if (userPriv == A) {
//get values from element 'Foo'
}
This way I can check once, and do the data gathering. The only solutions I can think of are setting the value of a hidden input element or use cookies.
<input type="hidden" id="userPriv" value="A" />
The other solution would be adding a value to the cookie.
setcookie("userPriv", "A");
Unfortunately, this last option gives me a warning message saying that cookie must be set in header (before html output). I think it's because I'm doing this in Wordpress.
I'm looking for opinions on which method is "the best way" to accomplis this.
Forgive me if I'm missing something, but checking for a DOM element in javascript is usually pretty easy.
var elementA = document.getElementById('id_of_a');
var elementB = document.getElementById('id_of_b');
if (elementA) {
//...
} else if (elementB) {
//...
}
The key is the if statement. getElementById will return nothing null if the element is not found, which will evaluate to false in the if statement.
Alternatively, if you don't really want to check for existence of individual DOM elements, can you send the users priv in a hidden input and act on that? That's a cookie free way of sending values clientside. Something like (edited to have jQuery code instead)
<input type="hidden" id="userPriv" value="A" />
...
var priv = $('#userPriv').val();
if (priv == 'A') {
//...
}
I'd still recommend checking for individual elements over checking a hidden input. It seems cleaner to me, more along the unobtrusive lines
You can use object as associative array:
var map = new Object();
map[A.toString()] = new Foo();
map[B.toString()] = new Bar();
In that case is much simpler to check and you will avoid "spaghetti code".

Locating text and performing operation based on its existence

I'm trying to learn jQuery, but it's coming slowly as I really don't know any JavaScript.
My site is in VB.NET and I'm putting jQuery code on both my actual .ascx UserControl and in a separate file (something like myscripts.js). This is because I'm using webforms as I still don't know MVC well enough to implement it, so I have to get the clientID's on the page.
What I would like to do is the following:
Grab text from a textbox and make it all lowercase
Get the username from the login info. I've done this like so on my actual page:
var userName = "<%=Split(System.Web.HttpContext.Current.User.Identity.Name.ToLowerInvariant, '|')%>";
Check to see if the username is in the text. If it IS in the text, I want to set a variable to "false", othewise to true.
How do I do this?
I am completely ignorant of the ASP.NET side of it, but as far as jQuery and Javascript....
To get the value of a text field, you use the jQuery function val():
var value = $('#mytextbox').val();
To turn a string to lower case, you use the string method toLowerCase():
var value = $('#mytextbox').val().toLowerCase();
Since val() returns a string we can throw that at the end.
To check if a string is within another string, you use the string method indexOf():
var needle = 'Hello';
var haystack = 'Hello World';
var match = haystack.indexOf(needle); // -1 if no matches, 0 in this case
Another thing to remember is that ASP.NET renames all your control ID's. To access your controls in JavaScript, you should use the following in place of the Control ID <%= txtUserName.ClientID %>.
In jQuery, here is what my selector would look like for a textbox with the ID "txtUserName".
$('#<%= txtUserName.ClientID %>')
Enjoy,
Zach
var userName = "username as it comes out of your web app";
// stuff happens
var $myTextbox = $('#ID_of_textbox');
var userNameIsContained = $myTextbox.val().toLowerCase().indexOf(userName) >= 0;
Short explanation:
$('#ID_of_textbox') // fetches the jQuery object corresponding to your textbox
.val() // the jQuery function that gets the textbox value
.toLowerCase() // self explanatory
.indexOf() // returns the position of a string in a string (or -1)
See the JavaScript String object reference at w3schools.
Alternative (to check if the textbox value equals the username):
var userNameIsEqual = $myTextbox.val().toLowerCase() == userName;
The basics of JQuery are like so: Find a list of dom elements, and perform actions on them.
In your case, you should start off by finding the dom element that is your testbox. For example's sake, we'll choose $('#userName'). The selector # means "id" and together with the name "userName" it finds all elements with the id of "userName". (Ids on a page should be unique if you're following best practices.)
Once you have that list (in this case, a list of one element), you can ask it what the value is.
$('#userName').val()
This gets you the value of the value="" attribute of the input tag.
You can then assign it to a variable and use standard javascript String functions to do the rest!
function checkLogin(userName){
return $('#mytextbox').val().toLowerCase() == userName
}
if ($("#textBoxID").val()) != "") { /*Do stuff*/ }

Categories