How to remove "undefined" from textboxes

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] || '';
}
1 Like

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);
}

That looks nice and simple. But when I tried it, I still get “undefined” in the fields.

Provide a link to the page, I suspect something else is at play here.

It’s an app built with HTML, CSS, and JS, so it’s not on a server. I’ll summarize it below:

The body tag:

<body onload="loadData()">

The textbox and button (there are 11 of these – Note1, Note2…):

<textarea id="Note1" cols="20" rows="4"></textarea>
<br>
<input type="button" value="Save your Note" onclick="persistData()" style="font-weight:bold; padding:5px 0">

Closing matter (the external JS of the OP is in the first script listed here):

<script src="localStorage-milestones.js"></script>
<script>
var execute = function () {
    //alert("executing code");    
};

if ( !!(window.addEventListener) )
window.addEventListener("DOMContentLoaded", execute)
else // MSIE
window.attachEvent("onload", execute)
</script>
</body>

The relevant localStorage-milestones.js:

var form1 = document.getElementById('form1');

function persistData()
{
    for (var i = 1; i <= 11; i++)
    {
        var storageIndex = "Milestones.html.note." + i;
        localStorage[storageIndex] = form1["Note" + i].value
    }
}

function loadData()
{
    for (var i = 1; i <= 11;  i++)
    {
        form1["Note" + i].value = localStorage["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]
}

Can you explain what the line is doing? Is it supposed to replace something else?

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).

Hopefully not too off-topic, would there be much difference between these two conditionals?

if (value === undefined)
if(typeof value == "undefined")

I think you are responding to Paul’s contribution, which I am not using at this time.

1 Like

Oh, I see what you did. Very clever. I’ll incorporate that! Thanks!

I wasn’t sure about that either.

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.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.