Writing Arrays To <select> Tag

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • LayneMitch via WebmasterKB.com

    Writing Arrays To <select> Tag

    Hello everyone.

    I'm currently learning Javascript and doing a few exercises.

    One problem I'm working on takes an array of names from an xml file using
    Ajax and writes it to <select<options tags.

    This is the code they use:



    function writeSelect(nam e_group) {
    var this_option;
    var my_select = document.getEle mentById("namel ist");
    for (var loop = 0; loop < name_group.leng th; loop++)
    {
    this_option = new Option();
    this_option.val ue = the_array[loop];
    this_option.tex t = the_array[loop]
    my_select.optio ns[loop] = this_option;
    }

    }


    The parameter for writeSelect() function contains the array of names and the
    id "namelist" is the id for the select tag in the form element.

    This is my first time seeing the new Option() function. Is this the standard
    for writing arrays to the <selecttag? Or could this have been done another
    way - if so what this that way?

    Any response would be appreciated.

    --
    Message posted via WebmasterKB.com


  • Bart Van der Donck

    #2
    Re: Writing Arrays To &lt;select&g t; Tag

    LayneMitch wrote:
    One problem I'm working on takes an array of names from an xml file using
    Ajax and writes it to <select<options tags.
    >
    This is the code they use:
    >
    function writeSelect(nam e_group) {
       var this_option;
       var my_select = document.getEle mentById("namel ist");
       for (var loop = 0; loop < name_group.leng th; loop++)
          {
            this_option = new Option();
            this_option.val ue = the_array[loop];
            this_option.tex t = the_array[loop]
            my_select.optio ns[loop] = this_option;
          }
    }
    >
    The parameter for writeSelect() function contains the array of names and the
    id "namelist" is the id for the select tag in the form element.
    >
    This is my first time seeing the new Option() function. Is this the standard
    for writing arrays to the <selecttag? Or could this have been done another
    way - if so what this that way?
    I'm afraid your function has a number of shortcomings.

    - A better backwards compatibility can be obtained by using
    'document.forms[0].elements["namelist"]' in stead of
    'document.getEl ementById("name list")'.
    - I surmise that your 'the_array' should read 'name_group'
    - It appears you want to do a full refill of the list, since you start
    looping from zero. But if your first list would be bigger than the new
    one, the last entries of the first list will still be shown. It would
    be better to empty the list first and then assign the new ones.
    - Inside the loop, you use four lines of code for what is usually done
    in one instruction.

    All together:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
    <html>
    <head>
    <script type="text/javascript">
    var arr = ['John', 'Paul', 'Fred', 'Mary'];
    function writeSelect(nam e_group) {
    var my_select = document.forms[0].elements['namelist'];
    // empty the list
    while (my_select.opti ons.length) my_select.optio ns[0] = null;
    // populate list with the new values
    for (var i=0; i<name_group.le ngth; ++i)
    my_select.optio ns[my_select.lengt h]
    = new Option(name_gro up[i], name_group[i]);
    }
    </script>
    <title>My web page</title>
    </head>
    <body>
    <form method="get" action="#">
    <p>
    <select size="1" name="namelist" >
    <option value="-">-</option>
    </select>
    <input type="button" value="Click" onClick="writeS elect(arr);">
    </p>
    </form>
    </body>
    </html>

    Info about the 'Option'-object:


    Hope this helps,

    --
    Bart

    Comment

    • Stanimir Stamenkov

      #3
      Re: Writing Arrays To &lt;select&g t; Tag

      Sat, 21 Jun 2008 05:26:33 -0700 (PDT), /Bart Van der Donck/:
      I've always wondered how standard (official or not) is the Option
      object? I mean isn't it better to use
      Document.create Element("option ") and the add() / remove() methods of
      the HTMLSelectEleme nt [1], or probably just Node.appendChil d() /
      Node.removeChil d()? I've not found references to the Option object
      in the "Gecko DOM Reference" [2] and the MSDN Library [3] - have I
      missed them?

      [1] http://www.w3.org/TR/DOM-Level-2-HTM...ml#ID-94282980
      [2] http://developer.mozilla.org/en/docs..._DOM_Reference
      [3] http://msdn.microsoft.com/library

      --
      Stanimir

      Comment

      • Bart Van der Donck

        #4
        Re: Writing Arrays To &lt;select&g t; Tag

        Stanimir Stamenkov wrote:
        Sat, 21 Jun 2008 05:26:33 -0700 (PDT), /Bart Van der Donck/:
        >
        >Info about the 'Option'-object:
        >http://www.javascriptkit.com/jsref/s...shtml#section2
        >
        I've always wondered how standard (official or not) is the Option
        object?
        The Option-object is one of the eldest around and was already
        supported in the first j(ava)script versions.
        I mean isn't it better to use Document.create Element("option ")
        and the add() / remove() methods of the HTMLSelectEleme nt [1],
        or probably just Node.appendChil d() / Node.removeChil d()?  
        This belongs to a more recent coding style, which aims to advocate a
        more general syntax. The benefit is that it's intended for the whole
        DOM of the page, and thus technically easier for the programmer. On
        the other hand, some could prefer a more classical approach too:
        longer proven history, better browser support, programmer is more
        confident in his old syntax, ...
        I've not found references to the Option object in the "Gecko DOM
        Reference" [2] and the MSDN Library [3] - have I missed them?
        Yes.

        --
        Bart

        Comment

        • Stanimir Stamenkov

          #5
          Re: Writing Arrays To &lt;select&g t; Tag

          Sat, 21 Jun 2008 07:51:39 -0700 (PDT), /Bart Van der Donck/:
          Stanimir Stamenkov wrote:
          >
          >I've not found references to the Option object in the "Gecko DOM
          >Reference" [2] and the MSDN Library [3] - have I missed them?
          >
          Yes.
          Could you be so kind and provide them for me? Thanks.

          --
          Stanimir

          Comment

          • Bart Van der Donck

            #6
            Re: Writing Arrays To &lt;select&g t; Tag

            Stanimir Stamenkov wrote:
            Sat, 21 Jun 2008 07:51:39 -0700 (PDT), /Bart Van der Donck/:
            >
            >Stanimir Stamenkov wrote:
            >
            >>I've not found references to the Option object in the "Gecko DOM
            >>Reference" [2] and the MSDN Library [3] - have I missed them?
            >
            >Yes.
            >
            Could you be so kind and provide them for me?  Thanks.
            The HTML element is used to define an item contained in a , an , or a element. As such, can represent menu items in popups and other lists of items in an HTML document.



            --
            Bart

            Comment

            • Stanimir Stamenkov

              #7
              Re: Writing Arrays To &lt;select&g t; Tag

              Sun, 22 Jun 2008 00:07:55 -0700 (PDT), /Bart Van der Donck/:
              The HTML element is used to define an item contained in a , an , or a element. As such, can represent menu items in popups and other lists of items in an HTML document.

              http://devedge-temp.mozilla.org/libr...ce/option.html
              Thanks. Perhaps I should have stated it more clear earlier. I was
              interested where the |Option()| constructor was documented. While
              the MSDN resource doesn't mention it, the older JavaScript 1.3
              Reference has it. I was puzzled why the newer documentation doesn't
              have it, but as Richard Cornford explained in another reply it is
              pretty much because "... manufacturer documentation tends to stress
              how its authors think things should be done in their own products...".

              --
              Stanimir

              Comment

              • Thomas 'PointedEars' Lahn

                #8
                Re: Writing Arrays To &lt;select&g t; Tag

                Bart Van der Donck wrote:
                Stanimir Stamenkov wrote:
                >Sat, 21 Jun 2008 05:26:33 -0700 (PDT), /Bart Van der Donck/:
                >>
                >>Info about the 'Option'-object:
                >>http://www.javascriptkit.com/jsref/s...shtml#section2
                >I've always wondered how standard (official or not) is the Option
                >object?
                >
                The Option-object is one of the eldest around and was already
                supported in the first j(ava)script versions.
                Evidently, while `Option' objects have been around since JavaScript 1.0,
                their constructor was not available before JavaScript 1.1. The unfortunate
                mix between the JavaScript core language and the Netscape Navigator DOM has
                been resolved as of JavaScript 1.4. Since JavaScript 1.5 this feature and
                other host objects are part of the Gecko DOM instead. (The Gecko DOM
                Reference at that, is incomplete. Since it is a public Wiki since quite a
                while, it can easily be made complete.)

                Evidently as well, the object has never been part of JScript. However, it
                is available at least since MSHTML 4.0.


                PointedEars
                --
                Use any version of Microsoft Frontpage to create your site.
                (This won't prevent people from viewing your source, but no one
                will want to steal it.)
                -- from <http://www.vortex-webdesign.com/help/hidesource.htm>

                Comment

                • Baris-C

                  #9
                  Re: Writing Arrays To &lt;select&g t; Tag

                  On Jun 21, 9:20 am, "LayneMitch via WebmasterKB.com " <u39402@uwe>
                  wrote:
                  Hello everyone.
                  >
                  I'm currently learning Javascript and doing a few exercises.
                  >
                  One problem I'm working on takes an array of names from an xml file using
                  Ajax and writes it to <select<options tags.
                  >
                  This is the code they use:
                  >
                  function writeSelect(nam e_group) {
                  var this_option;
                  var my_select = document.getEle mentById("namel ist");
                  for (var loop = 0; loop < name_group.leng th; loop++)
                  {
                  this_option = new Option();
                  this_option.val ue = the_array[loop];
                  this_option.tex t = the_array[loop]
                  my_select.optio ns[loop] = this_option;
                  }
                  >
                  }
                  >
                  The parameter for writeSelect() function contains the array of names and the
                  id "namelist" is the id for the select tag in the form element.
                  >
                  This is my first time seeing the new Option() function. Is this the standard
                  for writing arrays to the <selecttag? Or could this have been done another
                  way - if so what this that way?
                  >
                  Any response would be appreciated.
                  >
                  --
                  Message posted via WebmasterKB.com http://www.webmasterkb .com/Uwe/Forums.aspx/javascript/200806/1
                  function doselect()
                  {
                  document.write( "<select>") ;
                  for(var i = 0; i < array.legnth; i++)
                  {
                  document.write( "<option value ="+array[i]+">"+i+"</option>");
                  }
                  document.write( "</select>");

                  Comment

                  • Thomas 'PointedEars' Lahn

                    #10
                    Re: Writing Arrays To &lt;select&g t; Tag

                    Baris-C wrote:
                    function doselect()
                    {
                    document.write( "<select>") ;
                    for(var i = 0; i < array.legnth; i++)
                    {
                    document.write( "<option value ="+array[i]+">"+i+"</option>");
                    }
                    document.write( "</select>");
                    (sic!)

                    - Unnecessary and pointless: document.write( ) after load *overwrites*
                    - Syntactically wrong: ETAGO delimiters not escaped, missing `}'
                    - Typo: _length_
                    - Error-prone: consecutive document.write( ) for incomplete element
                    - Hopelessly inefficient: consecutive document.write( ),
                    repeated `length' lookup (if typo was corrected)
                    - Bad style: uses globals unnecessarily, whitespacing and indentation sucks

                    Next, please.


                    PointedEars
                    --
                    Anyone who slaps a 'this page is best viewed with Browser X' label on
                    a Web page appears to be yearning for the bad old days, before the Web,
                    when you had very little chance of reading a document written on another
                    computer, another word processor, or another network. -- Tim Berners-Lee

                    Comment

                    • Baris-C

                      #11
                      Re: Writing Arrays To &lt;select&g t; Tag

                      <script language="javas cript">

                      doselect();

                      function doselect()
                      {
                      try
                      {
                      var array = Array("select your value","bir","s uç
                      bende","yine"," cennet","zor güzel","A","yok ","insanlar","s us","sakýn
                      söyleme","ben", "aðla","göç ");

                      document.write( "<select>") ;
                      for(var i = 0; i < array.length; i++)
                      {
                      document.write( "<option value ="+i+">"+arr ay[i]+"</option>");
                      }

                      document.write( "</select>");
                      }

                      catch(e)
                      {
                      document.write( e.name+" : "+e.description );
                      }
                      }
                      </script>

                      Comment

                      • Thomas 'PointedEars' Lahn

                        #12
                        Re: Writing Arrays To &lt;select&g t; Tag

                        Baris-C wrote:
                        <script language="javas cript">
                        <http://validator.w3.or g/#validate-by-input>
                        doselect();
                        >
                        function doselect()
                        This is still unnecessary and pointless. If would only make sense if the
                        Array object reference would be passed instead, so that the method would
                        become general.
                        {
                        try
                        {
                        Unnecessary. Error-prone, because not universally supported. No statement
                        here is going to throw an exception.
                        var array = Array("select your value","bir","s uç
                        ^^^^^
                        Unwise choice for an identifier.
                        bende","yine"," cennet","zor güzel","A","yo k","insanlar"," sus","sakın
                        söyleme","ben" ,"ağla","göç ");
                        This should be passed as an argument (in the following: `a') instead.
                        document.write( "<select>") ;
                        for(var i = 0; i < array.length; i++)
                        {
                        document.write( "<option value ="+i+">"+arr ay[i]+"</option>");
                        }
                        >
                        document.write( "</select>");
                        }
                        Sigh. [psf 10.1]

                        function esc(s)
                        {
                        return String(s).repla ce(
                        /[<>&]/g,
                        function(m) { return "&#" + m.charCodeAt(0) + ";" });
                        }

                        var out = ['<select size="1">'];

                        for (var i = 0, len = a.length; i < len; i++)
                        {
                        // if Array.prototype .push() isn't available,
                        // augmentation needs to provide it
                        out.push('<opti on value="' + i + '"' + (i === 0 ? ' selected' : '')
                        + '>' + esc(a[i]) + '<\/option>');
                        }

                        out.push('<\/select>');

                        // "\n" for pretty printing
                        document.write( out.join("\n")) ;
                        catch(e)
                        {
                        document.write( e.name+" : "+e.description );
                        }
                        If document.write( ) throws an exception (which is the only statement that
                        could be expected to, in Gecko's XHTML DOM), what makes you think that
                        another document.write( ) call could be successful then? Even more, what
                        makes you think this message could be helpful to the user?


                        PointedEars
                        --
                        var bugRiddenCrashP ronePieceOfJunk = (
                        navigator.userA gent.indexOf('M SIE 5') != -1
                        && navigator.userA gent.indexOf('M ac') != -1
                        ) // Plone, register_functi on.js:16

                        Comment

                        • Stanimir Stamenkov

                          #13
                          Re: Writing Arrays To &lt;select&g t; Tag

                          Tue, 24 Jun 2008 03:51:33 -0700 (PDT), /Baris-C/:
                          document.write( "<select>") ;
                          for(var i = 0; i < array.length; i++)
                          {
                          document.write( "<option value ="+i+">"+arr ay[i]+"</option>");
                          }
                          document.write( "</select>");
                          Thomas Lahn already pointed in another reply invoking
                          document.write( ) after load overwrites the document but
                          document.write( ) also doesn't work with XHTML documents:



                          --
                          Stanimir

                          Comment

                          Working...