SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 29
  1. #1
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Populating one select option with localStorage is unsuccessful

    I am trying to add another option to the select drop-down, populated from a localStorage field. I haven't been successful. Here's my latest attempt:

    Code:
    <select size="1" name="testingSetup" id="testingSetup" onchange="document.formTesting.testingSetupLoad.value = this.value">
        <option value="">choose setup</option>
        <option value="setup 1">setup 1</option>
        <option value="setup 2">setup 2</option>
        <script type="text/javascript">
    var aboutSetup1 = localStorage.getItem('aboutSetup1'); formTesting.testingSetup.value += "\n <option value=\""+aboutSetup1+"\">"+aboutSetup1+"</option>"
        </script>
    </select>
    Google Chrome shows no errors, but it doesn't show the option, either. How do I populate a new option with a localStorage value with Javascript?

  2. #2
    Avid Logophile silver trophy
    ParkinT's Avatar
    Join Date
    May 2006
    Location
    Central Florida
    Posts
    2,343
    Mentioned
    192 Post(s)
    Tagged
    4 Thread(s)
    How about this?
    Code:
        <script type="text/javascript">
    var aboutSetup1 = localStorage.getItem('aboutSetup1'); 
        </script>
    <select size="1" name="testingSetup" id="testingSetup" onchange="document.formTesting.testingSetupLoad.value = this.value">
        <option value="">choose setup</option>
        <option value="setup 1">setup 1</option>
        <option value="setup 2">setup 2</option>
        <script> document.write("<option value=\""+aboutSetup1+"\">"+aboutSetup1+"</option>");</script>
    </select>
    Don't be yourself. Be someone a little nicer. -Mignon McLaughlin, journalist and author (1913-1983)


    Git is for EVERYONE
    Literally, the best app for readers.
    Make Your P@ssw0rd Secure
    Leveraging SubDomains

  3. #3
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thanks, but Google still displays a blank page (so does FF). No errors.

  4. #4
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    I believe you want this:
    Code:
    var aboutSetup1 = localStorage.getItem('aboutSetup1'); 
    formTesting.testingSetup.options[formTesting.testingSetup.options.length] = new Option(aboutSetup1, aboutSetup1);

  5. #5
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    No, the drop-down still doesn't show the option. I have:

    Code:
      <script type="text/javascript">
    var aboutSetup1 = localStorage.getItem('aboutSetup1'); 
    formTesting.testingSetup.option[formTesting.testingSetup.option.length] = new option(aboutSetup1, aboutSetup1);</script>
                <select size="1" name="testingSetup" id="testingSetup" onchange="document.formTesting.testingSetupLoad.value = this.value">
                                    <option value="">choose setup</option>
                                    <option value="setup 1">setup 1</option>
                                    <option value="setup 2">setup 2</option>
                </select>
    At least the screen is no longer blank.

  6. #6
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    You need to run it in the onload event, or the domReady event.
    Code:
    window.onload = function() { var aboutSetup1 = localStorage.getItem('aboutSetup1'); 
    formTesting.testingSetup.option[formTesting.testingSetup.option.length] = new option(aboutSetup1, aboutSetup1); }

  7. #7
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    Also you copied and pasted my code incorrectly, where I have options, you have option, and where I have Option you have option.
    Proof of Concept: http://jsfiddle.net/cpradio/YFdjf/

  8. #8
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I put this in the head:

    Code:
    window.onload = function() { 
    var aboutSetup1 = localStorage.getItem('aboutSetup1'); 
    formTesting.testingSetup.option[formTesting.testingSetup.option.length] = new option(aboutSetup1, aboutSetup1); 
    var aboutSetup1 = localStorage.getItem('aboutSetup1'); 
    formTesting.testingSetup.options[formTesting.testingSetup.options.length] = new Option(aboutSetup1, aboutSetup1);
    }
    and the select section is now:
    Code:
    <script type="text/javascript">
    var aboutSetup1 = localStorage.getItem('aboutSetup1'); 
    formTesting.testingSetup.options[formTesting.testingSetup.options.length] = new Option(aboutSetup1, aboutSetup1);</script>
                <select size="1" name="testingSetup" id="testingSetup" onchange="document.formTesting.testingSetupLoad.value = this.value">
                                    <option value="">choose setup</option>
                                    <option value="setup 1">setup 1</option>
                                    <option value="setup 2">setup 2</option>
                </select>
    Google tools says, "Uncaught TypeError: Cannot read property 'options' of undefined"

  9. #9
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    1) Remove the script tag from your HTML markup. That is no longer necessary.
    2) To fix the Error, you need to replace formTesting with the name of your <form> element.

  10. #10
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I removed all the <script></script> information from the select.

    The form name is correct: formTesting. (All my form names are prefixed with "form.")

    I corrected the misspelled var. I entered data into the variable. The variable still doesn't appear in the dropdown. No errors in Chrome now. Now reads:

    window.onload = function() {
    var aboutSetupOne = localStorage.getItem('aboutSetupOne');
    formTesting.testingSetup.options[formTesting.testingSetup.options.length] = new Option(aboutSetupOne, aboutSetupOne);
    }

  11. #11
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    My guess is your localStorage is either an empty string, null, or doesn't exist.
    http://jsfiddle.net/cpradio/YFdjf/

    My proof of concept code now handles when the localStorage is null. You may want to put something like console.log(localStorage.getItem('aboutSetupOne')); and open the Developer tools to see what it outputs.

  12. #12
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Do I need to sign in to jsfiddle to make it work? Clicking on the drop-down box does not show anything other than setup 1 and setup 2 in the options. 'Testing' does not appear for me.

    Adding the console code shows the var content successfully, so the var content is in memory. It's just not among the options.

    Thanks for helping.

  13. #13
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    What browser are you using? I am using Chrome v17 Portable, and in the Result pane I see Testing as the third option

  14. #14
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I was using FF. I just tried it in Chrome and I see Testing as the third option. Unfortunately, this code is being run on the iPhone and it has to work there, on Webkit browsers. Since it works on Chrome, it should work on the iPhone. Still need to study this...

  15. #15
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    I can't comment on the iPhone, I don't do any phone development. What I can say, is the code should work on just about any browser (not sure why it failed in Firefox -- I'll take a look as that bothers me; maybe FF doesn't support localStorage?).

  16. #16
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,222
    Mentioned
    153 Post(s)
    Tagged
    0 Thread(s)
    Got the FF issue resolved. Seems it was failing to load jQuery (due to needing to use POST instead of GET). I just changed the framework to MooTools (since we aren't using a framework, the framework is really unnecessary).

    I also had to use document.formTesting instead of just formTesting.

  17. #17
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    <select size="1" name="testingSetup" id="testingSetup" onchange="document.formTesting.testingSetupLoad.value = this.value">
        <option value="">choose setup</option>
        <option value="setup 1">setup 1</option>
        <option value="setup 2">setup 2</option>
    </select>
    
    <script type="text/javascript">
    
     var aboutSetup1 = localStorage ? localStorage.getItem( 'aboutSetup1' ) : null; 
     
     if( aboutSetup1 )
       document.getElementById( "testingSetup" ).options.add( new Option( aboutSetup1, aboutSetup1 ) );     
      
     // localStorage.setItem( 'aboutSetup1', 'The_New_Option' );
     
    </script>
    Tab-indentation is a crime against humanity.

  18. #18
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    FF does support localstorage. The good news is that the iPhone understands Javascript just fine!

  19. #19
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I'm using Jquery Mobile.

    Chrome sees no errors in your #17 code, but I don't see the new options in the drop-down, either. Thanks for responding!

  20. #20
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by StevenHu View Post
    I'm using Jquery Mobile.

    Chrome sees no errors in your #17 code, but I don't see the new options in the drop-down, either. Thanks for responding!
    What do you see if you execute the following line in Chrome's address bar?

    javascript:str="localStorage%20content\n\n";for(var%20x%20in%20localStorage){void(str+=x+'%20:%20'+localStorage[x]+'\n')}alert(str)

    Note that when you paste the above line into the address bar, javascript: will probably be stripped-out and will need to be replaced before pressing Enter.

    You should get an alert of all current localStorage content.
    Tab-indentation is a crime against humanity.

  21. #21
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    No matter how many times I type Javascript: before the line, Chrome strips it out, sorry.

    I have a script on another page running the following to fill a textarea...

    var aboutSetupOne = localStorage.getItem('aboutSetupOne');
    form2.summaries.value += "***SUMMARIES***\n" + aboutSetupOne;

    ... and it's filled in with a string, no problem there.

  22. #22
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    OK THIS WORKS!!

    <select size="1" name="testingSetup" id="testingSetup" onchange="document.formTesting.testingSetupLoad.value = this.value">
    <option value="">choose setup</option>
    <option value="setup 1">setup 1</option>
    <option value="setup 2">setup 2</option>
    </select>

    <script type="text/javascript">
    var aboutSetupOne = localStorage ? localStorage.getItem( 'aboutSetupOne' ) : null;

    if( aboutSetupOne )
    document.getElementById( "testingSetup" ).options.add( new Option( aboutSetupOne, aboutSetupOne ) );

    // localStorage.setItem( 'aboutSetupOne', 'aboutSetupOne' );

    Thank you very much!
    </script>

  23. #23
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by StevenHu View Post
    OK THIS WORKS!!

    <select size="1" name="testingSetup" id="testingSetup" onchange="document.formTesting.testingSetupLoad.value = this.value">
    <option value="">choose setup</option>
    <option value="setup 1">setup 1</option>
    <option value="setup 2">setup 2</option>
    </select>

    <script type="text/javascript">
    var aboutSetupOne = localStorage ? localStorage.getItem( 'aboutSetupOne' ) : null;

    if( aboutSetupOne )
    document.getElementById( "testingSetup" ).options.add( new Option( aboutSetupOne, aboutSetupOne ) );

    // localStorage.setItem( 'aboutSetupOne', 'aboutSetupOne' );

    Thank you very much!
    </script>
    Now for some cleaning up.

    Move the onchange event out of the HTML code, and in to the scripting where it belongs.
    Remove the id attribute from select. When the select field is within the form, it should be accessed from the form's elements collection.
    Removing also the size attribute, since that is only used when the multiple attribute is also given.

    Code html4strict":
    <select name="testingSetup">
        ...
    </select>

    Also, assigning testingSetup to a local variable, since we're now using it from multiple places

    Code javascript:
    var form = document.getElementById('formTesting'),
        testingSetup = form.elements.testingSetup,
    ...
    testingSetup.onchange = function () {
        ...
    };

    Assuming that the form has an id of "formTesting" on it, that is the point of access we should use in order to access all of the form elements.
    When we're already within the form, we can use this.form to easily access the form instead.

    Code javascript:
    testingSetup.onchange = function () {
        var form = this.form;
        form.elements.testingSetupLoad.value = this.value;
    };

    Next with aboutSetupOne, there is no given benefit to assign null to the value, so instead of using a ternary operator, we can use a guard condition which serves the same purpose, and makes our intentions crystal clear - that we are protecting against situations where localStorage is not supported.

    Code javascript:
    var ...,
        aboutSetupOne = localStorage && localStorage.getItem( 'aboutSetupOne' );

    Lastly, always use braces for statement blocks, even if there is only one statement within them.
    Not only does that protect you when you add another line to it, but it's also a consistant behaviour, which when missing acts as an instant warning of potential issues.

    Code javascript:
    if (aboutSetupOne) {
        testingSetup.options.add(new Option(aboutSetupOne, aboutSetupOne)); 
    }

    Which means that we end up with something like this:

    Code javascript:
    <form id="formTesting">
        <select name="testingSetup">
            <option value="">choose setup</option>
            <option value="setup 1">setup 1</option>
            <option value="setup 2">setup 2</option>
        </select>
        ...
        <input name="testingSetupLoad">
    </form>

    Code javascript:
    var form = document.getElementById('formTesting'),
        testingSetup = form.elements.testingSetup,
        aboutSetupOne = localStorage && localStorage.getItem('aboutSetupOne');
     
    if (aboutSetupOne) {
        testingSetup.options.add(new Option(aboutSetupOne, aboutSetupOne)); 
    }
     
    // localStorage.setItem('aboutSetupOne', 'aboutSetupOne');
     
    testingSetup.onchange = function () {
        var form = this.form;
        form.elements.testingSetupLoad.value = this.value;
    };
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  24. #24
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    Next with aboutSetupOne, there is no given benefit to assign null to the value,
    It's a good practice that avoids having to use typeof to avoid the error if( aboutSetupOne ), where the operand is undefined.

    so instead of using a ternary operator, we can use a guard condition which serves the same purpose, and makes our intentions crystal clear - that we are protecting against situations where localStorage is not supported.

    Code javascript:
    var ...,
        aboutSetupOne = localStorage && localStorage.getItem( 'aboutSetupOne' );
    We need to guard against doing that, because ANDing operands that could be undefined will generate an error:

    Code:
    aboutSetupOne = _localStorage && _localStorage.getItem( 'aboutSetupOne' );  //ERROR
    Tab-indentation is a crime against humanity.

  25. #25
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Logic Ali View Post
    It's a good practice that avoids having to use typeof to avoid the error if( aboutSetupOne ), where the operand is undefined.
    When the operand is undefined, if(aboutSetupOne) is still falsy - there's no need to define the variable as being null.

    Quote Originally Posted by Logic Ali View Post
    We need to guard against doing that, because ANDing operands that could be undefined will generate an error:
    No they won't. With:

    Code:
    aboutSetupOne = localStorage && localStorage.getItem( 'aboutSetupOne' );
    JavaScript checks the first operand, and only if it's truthy does JavaScript then check the second operand. No errors are generated.
    This is why in JavaScript the && operator is also called the "guard operator".

    Please try to not bring inappropriate practices from other programming languages in to your JavaScript coding.
    English spoken with a French accept can be quite wonderful. JavaScript written with influences from other languages isn't.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •