I understand that “undefined” in textboxes indicates hat it has no value. But it looks ugly in the textbox and I don’t want my users hitting the backspace button to delete the text. I thought of doing it the following way, but “undefined” is still showing up.
I dump the localstorage value into check and check whether it is undefined. If it is (because the user hasn’t added anything to the textbox), add a dash to the box. if it is not, show the value.
function loadData()
{
for (var i = 1; i <= 11; i++){
var check = localStorage["Milestones.html.note." + i];
if (check === undefined) {
form1["Note" + i].value = '-';
}else{
form1["Note" + i].value = localStorage["Milestones.html.note." + i];
}
}
}
I also tried if (check.length == 0) { and it still showed “undefined.” I am not getting any errors in the console, so the code is doing it’s job otherwise.
How do I keep the textbox blank until something is entered in?
When fetching something from localStorage you can provide another value if it’s undefined.
Undefined being “falsy” you can use the || operator to provide an empty string as a default.
for (var i = 1; i <= 11; i++){
form1["Note" + i].value = localStorage["Milestones.html.note." + i] || '';
}
There are some values though such as “0” that are also considered to be falsy, so it can be better to check more explicitly for undefined.
for (var i = 1; i <= 11; i += 1) {
var value = localStorage["Milestones.html.note." + i];
if (value === undefined) {
value = "";
}
form1["Note" + i].value = value;
}
And you can make the code easier to understand, by moving the guts of the for loop out to a separate function:
function getLocalStorageValue(item) {
var value = localStorage[item];
if (value === undefined) {
value = "";
}
return value;
}
for (var i = 1; i <= 11; i += 1) {
form1["Note" + i].value = getLocalStorageValue("Milestones.html.note." + i);
}
Well well, the “undefined” are all gone! I don’t know why it is working now and not earlier at the time I posted the last code, but I am crediting markbrown4 for the solution, which I had incorporated. Thanks!
As an unsolicited side note, I wouldn’t hard-code this information into the script like that – it makes your code harder to maintain, reuse and debug. Instead, you could access the number of the elements like so:
var notes = document.querySelectorAll('[id^="Note"]');
for (var i = 1; i <= notes.length; i++) {
// do something with notes[i]
}
You have a NodeList of all elements with an id that starts with “Note” and access its length in the for loop. This way you don’t have to tell your script how many there are (like: exactly 11).
Apparently typeof is useful for checking global variables that you haven’t created a var for.
Once you have declared a variables typeof value == 'undefined' and value === undefined are equivalent. Personally, I had always used the typeof check - I guess that’s because it always works.