Results 1 to 3 of 3

Thread: Populate option of <select>

  1. #1
    Join Date
    Nov 2005
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Populate option of <select>

    Hi All,

    I have an array1 like this :

    var array1 =
    [["Select Number"],
    ["One"],
    ["Two"]]

    How do I code, so array1 elements will populate onLoad the options of <select> like :

    <select name="s1">
    <option name="option1">One
    <option name="option2">Two
    </select>

    Thanks in advance.
    Amri

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,375
    Thanks
    77
    Thanked 3,421 Times in 3,382 Posts
    Blog Entries
    12

    Default

    Name is not a valid attribute of the option element so, I have used id instead. In other words, the created options will have the id of option0, option1, option2 - rather than name.

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript">
    onload=function(){
    var array1 = 
    ["[Select Number]",
    "One",
    "Two"]
    for (var i_tem = 0; i_tem < array1.length; i_tem++){
    array1[i_tem]=[array1[i_tem], document.createElement('option')]
    array1[i_tem][1].id='option'+i_tem
    array1[i_tem][1].appendChild(document.createTextNode(array1[i_tem][0]))
    document.getElementById('toFill').appendChild(array1[i_tem][1])
    }
    }
    </script>
    </head>
    <body>
    <select id="toFill" name="s1" onchange="alert(this.options[this.selectedIndex].id)">
    </select>
    </body>
    </html>
    The onchange event for the select is just a test to see if the id attributes were correctly assigned.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Nov 2005
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Hi jscheuer1,

    Wow, it was a quick answer . Appreciated your help in sovling my problem.
    I will implement your code and backwith later with result.

    Thans again and may God bless you.

    Amri

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
  •