Google analytics code

Thursday, October 8, 2009

Javascript: Adding options to a select element

I've started working with javascript more and more now. I'm leaning away from using innerHTML and started creating the objects instead. As with anything javascript related Internet Explorer will cause more problems than solutions.

When you're creating a new option element that will be added to a select element IE wants to do it one way while everyone else can handle it another way. I'll show the first way I tried to tackle it, and then show the cross browser way to handle it.

I set up a try, catch block that would try IE first. If an error occurred it would fall back to the second method that works in most browsers.


//IE code
try
{
obj_option = document.createElement('<option value="test value"/>');
obj_text = document.createTextNode("option text value");
obj_option.appendChild(obj_text);
}
//everyone else
catch(e)
{
var obj_option = document.createElement('option');

obj_option.text = "option text value";
obj_option.value = "test value";
}


Internet Explorer wants to place the value inside of the createElement method while other browsers can handle the assignment on the object property. Also IE wants the text added with createTextNode. It's a pain to have two methods for something so simple. After a bit of experimentation and research I have a method that works for all browsers.


var obj_option;
var obj_text;

obj_option = document.createElement('option');
obj_text = document.createTextNode("option text value");
obj_option.appendChild(obj_text);
obj_option.setAttribute("value", "test value");


This is much cleaner and easier to maintain. setAttribute is also a handy method for assigning non standard properties to an object. Some client-side form validation scripts want to add proprietary properties to a tag. Using setAttribute is the easiest way to create them.

3 comments:

  1. It's a bit barftastic, but this method also works:

    var sel = $('target_select');
    sel.options[sel.options.length] = new Option("Label", "Value");
    // etc.

    (wtb markdown formatting, qq)

    ReplyDelete
  2. That's a good jQuery way to do it. I use it quite a bit in projects for events, ajax and binding, but still use native js methods for a lot of things. That way it I could reuse something in a project that wanted to use another toolkit for some reason.

    ReplyDelete
  3. metric, thanks..this works very well, thanks a lot, you saved me hours :) by the way how much does the rose rabbit with three ears costs(if I am allowed to call it so) ? ;)

    thanks again

    ReplyDelete

If you found this page useful, or you have any feedback, please leave a comment.