SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Guru in training bronze trophy SoulScratch's Avatar
    Join Date
    Apr 2006
    Location
    Maryland
    Posts
    1,838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Appending <options> to a <select>

    I've played around (Linux Firefox - no access to MSIE) and figured out there are 3 ways of adding an option. Those would be appendChild on the selectElement, the .add method on either the selectElement or the .options collection, and manually setting selectRef.options[selectRef.options.length] to equal an option element. Could someone who's had experience with these explain what the benefit of one way is over the other? As I haven't been able to test in MSIE I'm pretty sure at least one of the three aren't reliable in IE.

  2. #2
    SitePoint Enthusiast elena_sev's Avatar
    Join Date
    Apr 2003
    Location
    Sofia, Bulgaria
    Posts
    64
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi there

    Recentrly I had to do this task too. My application is working on IE6 and IE7 but this function is working fine on Firefox and Safari so it should be ok for linux browsers too.

    Code:
    var box = document.getElementById('selectbox');
    box.options[box.options.length] = new Option('name','id');
    I've never used any of the other methods but this work fine for me. I hope I was helpful.

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    100 Post(s)
    Tagged
    4 Thread(s)
    The appendChild technique uses the standard DOM method to manipulate the DOM. Other techniques have been made available for better understanding of the code, but they have their issues. This is why the appendChild manner is most commonly used.

    The add method can be troublesome, because the second mandetory parameter is the object before it is inserted (or null for the end of the list).
    If you're using IE however, the second parameter is optional, and is an index number instead of where to place the element.

    The add method isn't used for good cross-compatible reasons.

    Changing things through selectRef.options may have cross-browser issues, as it's an object collection that's supposed to be readonly, not an array itself.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


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
  •