Page 1 of 2 12 LastLast
Results 1 to 10 of 18

Thread: Adding Options to a Select element

  1. #1
    Join Date
    Nov 2006
    Location
    Northeast USA
    Posts
    408
    Thanks
    8
    Thanked 30 Times in 28 Posts

    Default Adding Options to a Select element

    Hello,
    I googled this topic and got some code, but It does not seam to be working:
    Code:
    document.getElementById("SelectList").options[i] = new Option('new text','new value');
    with SelectList being the select element.
    When I load the page "ERROR: Line xxx: Object Expected."
    I am calling it inside a function, I don't know if that means anything but...
    Also I read that it will overwrite anything that is already there, Is there a way to make it so that It justs adds to the list? Thanks,
    -Ben -- THE DYNAMIC DRIVERS
    My Links: My DD Profile||My Youtube Video Tutorials||DD Helping Coders||DD Coders In Training
    I told my client to press F5, the client pressed F, then 5, *facepalm*

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    As far as I know:

    Code:
    new Option
    would have to refer to a function named Option. Go back to where you found this code and find the function.

    Using the DOM, you can add an option element to a select element:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript">
    function Option(t,v){
    var ot=document.createTextNode(t);
    var o=document.createElement('option')
    o.value=v;
    o.appendChild(ot);
    return o;
    }
    </script>
    </head>
    <body>
    <form action="#">
    <div>
    <input type="button" value="add"
    onclick="document.getElementById('test').appendChild(new Option('new text','new value'));">
    <br>
    <select id="test" name="something">
    <option value="existing value">existing text</option>
    </select><br>
    <input type="submit" value="Go!">
    </div>
    </form>
    </body>
    </html>
    - John
    ________________________

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

  3. #3
    Join Date
    Nov 2006
    Location
    Northeast USA
    Posts
    408
    Thanks
    8
    Thanked 30 Times in 28 Posts

    Default

    Thanks,
    I tried your example and it works! But as soon as I change it to fit my page, It says that document.getElementById("SelectList"); is null or not an object. YES there is a select list on this page with an ID like this. I use another script on this select box and it has no problem with getElementById("SelectList");.
    Maybe it's the changes that I made? I am not using a button to call it, I call it inside a function, and it's supposed to each time the function is run, add a new option to the select element.
    Edit:
    While I was writing this post, I think I figured out whats going on, but not how to stop it. I think that when It is called inside a function, it goes nuts because it is not being called on the document as was your example was. How can I solve this problem?
    -Ben -- THE DYNAMIC DRIVERS
    My Links: My DD Profile||My Youtube Video Tutorials||DD Helping Coders||DD Coders In Training
    I told my client to press F5, the client pressed F, then 5, *facepalm*

  4. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Don't be thinking like that. Just because something is inside a function doesn't mean it cannot find an element. However, if the function is executed before the element is parsed, there will be problems.

    Also, I wouldn't rule out typos or other "stupid" mistakes, or just something I'm not thinking of because I cannot see the full code. If you need more help:

    Please post a link to the page on your site that contains the problematic code so we can check it out.
    - John
    ________________________

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

  5. #5
    Join Date
    Nov 2006
    Location
    Northeast USA
    Posts
    408
    Thanks
    8
    Thanked 30 Times in 28 Posts

    Default

    Thanks, I ended up creating two functions, one function to print the varables, and one to add it to the select list (If you have no idea what I am talking about, you would have had to have seen the document, PS: I am running the script locally so I cannot post a link ). Anyways Everything Works, I mean ALMOST Everything works, and the one thing that does not work is a BIG ONE. Another script on my page, Pick list(http://www.javascriptkit.com/script/...picklist.shtml) Scans the HTML for options, but when ANY thing is added: "Runtime error on line XX: Object doesn't support this property or method" when the user clicks "->" to move one option to another select field. On that line:while (selectIndex > -1). *slaps head* Is there any way to fix this?
    -Ben -- THE DYNAMIC DRIVERS
    My Links: My DD Profile||My Youtube Video Tutorials||DD Helping Coders||DD Coders In Training
    I told my client to press F5, the client pressed F, then 5, *facepalm*

  6. #6
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I'm not having that problem:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript">
    function addOpt(f, e, t, v){
    var el=f.form.elements[e], Option=function(t,v){
    var ot=document.createTextNode(t), o=document.createElement('option')
    o.value=v; o.appendChild(ot); return o;
    }
    el.appendChild(new Option(t,v));
    }
    
    // PickList script- By Sean Geraty (http://www.freewebs.com/sean_geraty/)
    // Visit JavaScript Kit (http://www.javascriptkit.com) for this JavaScript and 100s more
    // Please keep this notice intact
    
    // Control flags for list selection and sort sequence
    // Sequence is on option value (first 2 chars - can be stripped off in form processing)
    // It is assumed that the select list is in sort sequence initially
    var singleSelect = true;  // Allows an item to be selected once only
    var sortSelect = true;  // Only effective if above flag set to true
    var sortPick = true;  // Will order the picklist in sort sequence
    
    // Initialise - invoked on load
    function initIt() {
      var selectList = document.getElementById("SelectList");
      var selectOptions = selectList.options;
      var selectIndex = selectList.selectedIndex;
      var pickList = document.getElementById("PickList");
      var pickOptions = pickList.options;
      pickOptions[0] = null;  // Remove initial entry from picklist (was only used to set default width)
      if (!(selectIndex > -1)) {
        selectOptions[0].selected = true;  // Set first selected on load
        selectOptions[0].defaultSelected = true;  // In case of reset/reload
      }
      selectList.focus();  // Set focus on the selectlist
    }
    
    // Adds a selected item into the picklist
    function addIt() {
      var selectList = document.getElementById("SelectList");
      var selectIndex = selectList.selectedIndex;
      var selectOptions = selectList.options;
      var pickList = document.getElementById("PickList");
      var pickOptions = pickList.options;
      var pickOLength = pickOptions.length;
      // An item must be selected
      while (selectIndex > -1) {
        pickOptions[pickOLength] = new Option(selectList[selectIndex].text);
        pickOptions[pickOLength].value = selectList[selectIndex].value;
        // If single selection, remove the item from the select list
        if (singleSelect) {
          selectOptions[selectIndex] = null;
        }
        if (sortPick) {
          var tempText;
          var tempValue;
          // Sort the pick list
          while (pickOLength > 0 && pickOptions[pickOLength].value < pickOptions[pickOLength-1].value) {
            tempText = pickOptions[pickOLength-1].text;
            tempValue = pickOptions[pickOLength-1].value;
            pickOptions[pickOLength-1].text = pickOptions[pickOLength].text;
            pickOptions[pickOLength-1].value = pickOptions[pickOLength].value;
            pickOptions[pickOLength].text = tempText;
            pickOptions[pickOLength].value = tempValue;
            pickOLength = pickOLength - 1;
          }
        }
        selectIndex = selectList.selectedIndex;
        pickOLength = pickOptions.length;
      }
      selectOptions[0].selected = true;
    }
    
    // Deletes an item from the picklist
    function delIt() {
      var selectList = document.getElementById("SelectList");
      var selectOptions = selectList.options;
      var selectOLength = selectOptions.length;
      var pickList = document.getElementById("PickList");
      var pickIndex = pickList.selectedIndex;
      var pickOptions = pickList.options;
      while (pickIndex > -1) {
        // If single selection, replace the item in the select list
        if (singleSelect) {
          selectOptions[selectOLength] = new Option(pickList[pickIndex].text);
          selectOptions[selectOLength].value = pickList[pickIndex].value;
        }
        pickOptions[pickIndex] = null;
        if (singleSelect && sortSelect) {
          var tempText;
          var tempValue;
          // Re-sort the select list
          while (selectOLength > 0 && selectOptions[selectOLength].value < selectOptions[selectOLength-1].value) {
            tempText = selectOptions[selectOLength-1].text;
            tempValue = selectOptions[selectOLength-1].value;
            selectOptions[selectOLength-1].text = selectOptions[selectOLength].text;
            selectOptions[selectOLength-1].value = selectOptions[selectOLength].value;
            selectOptions[selectOLength].text = tempText;
            selectOptions[selectOLength].value = tempValue;
            selectOLength = selectOLength - 1;
          }
        }
        pickIndex = pickList.selectedIndex;
        selectOLength = selectOptions.length;
      }
    }
    
    // Selection - invoked on submit
    function selIt(btn) {
      var pickList = document.getElementById("PickList");
      var pickOptions = pickList.options;
      var pickOLength = pickOptions.length;
      if (pickOLength < 1) {
        alert("No Selections in the Picklist\nPlease Select using the [->] button");
        return false;
      }
      for (var i = 0; i < pickOLength; i++) {
        pickOptions[i].selected = true;
      }
      return true;
    }
    
    </script>
    </head>
    <body onload="initIt();">
    <form NAME="theform" ID="theform" ACTION="whatever" onSubmit="return selIt();">
    <table>
    <tr>
    <td>
    <input type="button" value="add" onclick="addOpt(this,'SelectList','new text','new value');">
    <br><select NAME="SelectList" ID="SelectList" SIZE="5" multiple="multiple" style="width: 150px">
    <option VALUE="01sel">Selection 01</option>
    <option VALUE="02sel">Selection 02</option>
    
    <option VALUE="03sel">Selection 03</option>
    <option VALUE="04sel">Selection 04</option>
    <option VALUE="05sel">Selection 05</option>
    <option VALUE="06sel">Selection 06</option>
    <option VALUE="07sel">Selection 07</option>
    <option VALUE="08sel">Selection 08</option>
    <option VALUE="09sel">Selection 09</option>
    <option VALUE="10sel">Selection 10</option>
    </select>
    
    </td>
    <td>
    <input type="button" value="->" onclick="addIt();">
    <br>
    <input type="button" value="<-" onclick="delIt();">
    </td>
    <td>
    <select NAME="PickList" ID="PickList" SIZE="5" multiple="multiple" style="width: 150px">
    <option VALUE="01sel">Selection 01</option>
    </select>
    </td>
    </tr>
    <tr>
    <td ALIGN="left">
    <input TYPE="reset" VALUE="Reset" ONCLICK="javascript: window.location.href = 'picklist.html'">
    </td>
    
    <td>
    </td>
    <td ALIGN="right">
    <input TYPE="submit" VALUE="Submit">
    </td>
    </tr>
    </table>
    </form>
    </body>
    </html>
    - John
    ________________________

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

  7. #7
    Join Date
    Nov 2006
    Location
    Northeast USA
    Posts
    408
    Thanks
    8
    Thanked 30 Times in 28 Posts

    Default

    Did you try to remove all the options?
    ERROR: Runtime error on line 73
    --------------------------------------------------
    IT DOESN'T WORK ANY MORE!!!
    Even when I removed the code that added the exta value. Huh, I will Attach the full source, and remove it after you've looked at it, for saftey reasons.
    WHAT IS GOING ON?!?
    (note that images/songs are not included in this file)
    P.S. you have to change the extension from .txt to .htm
    -Ben -- THE DYNAMIC DRIVERS
    My Links: My DD Profile||My Youtube Video Tutorials||DD Helping Coders||DD Coders In Training
    I told my client to press F5, the client pressed F, then 5, *facepalm*

  8. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Removing all options causes an error even without my code. But the error I got was for this line:

    Code:
    selectOptions[0].selected = true
    which appears in two places, and it was the second one where the problem was. The first one is near where you got the error, so might as well add this in both places (additions red):

    Code:
      if (selectOptions[0] && !(selectIndex > -1)) {
        selectOptions[0].selected = true;  // Set first selected on load
        selectOptions[0].defaultSelected = true;  // In case of reset/reload
      }
    Then later:

    Code:
    if(selectOptions[0])
      selectOptions[0].selected = true;
    }
    
    // Deletes an  . . .
    - John
    ________________________

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

  9. #9
    Join Date
    Nov 2006
    Location
    Northeast USA
    Posts
    408
    Thanks
    8
    Thanked 30 Times in 28 Posts

    Default

    You Missunderstood, I was tring to tell you that when I implicated my script to yours, it did not work. It did not solve MY problem. There is no way I am re-implimenting the Picklist script, I have added so much stuff to it. Did you try to run the file? It says that there is somthing wrong with this while loop that wasn't before:
    Code:
    while (selectIndex > -1) {
    				pickOptions[pickOLength] = new Option(selectList[selectIndex].text);
    				pickOptions[pickOLength].value = selectList[selectIndex].value;
    				// If single selection, remove the item from the select list
    				if (singleSelect) {
    				  selectOptions[selectIndex] = null;
    				}
    				if (sortPick) {
    				  var tempText;
    				  var tempValue;
    				  // Sort the pick list
    				  while (pickOLength > 0 && pickOptions[pickOLength].value < pickOptions[pickOLength-1].value) {
    					tempText = pickOptions[pickOLength-1].text;
    					tempValue = pickOptions[pickOLength-1].value;
    					pickOptions[pickOLength-1].text = pickOptions[pickOLength].text;
    					pickOptions[pickOLength-1].value = pickOptions[pickOLength].value;
    					pickOptions[pickOLength].text = tempText;
    					pickOptions[pickOLength].value = tempValue;
    					pickOLength = pickOLength - 1;
    				  }
    				}
    IDK?
    -Ben -- THE DYNAMIC DRIVERS
    My Links: My DD Profile||My Youtube Video Tutorials||DD Helping Coders||DD Coders In Training
    I told my client to press F5, the client pressed F, then 5, *facepalm*

  10. #10
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I will look at your file when I have more time. Did you try adding the test(s) I suggested? They are pretty straightforward, and you would had to have radically altered the original javascriptkit script for them to no longer apply. They simply test to see if the element is available before taking action, a good practice in any script.
    - John
    ________________________

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

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
  •