Skip to content Skip to sidebar Skip to footer

Shortcut For Document.createelement("option")?

My function clears out a dropdownlist and then re-populates it. Do I really need all this or is there a more concise way to do this? Meaning do I need to create a new document.cr

Solution 1:

var new_option_element = new Option(display_label, value, selected_boolean);

Solution 2:

Create your own shortcut...

functionx() { returndocument.createElement("option"); }

for(blah blah blah) {
  objNewOption = x();
}

Solution 3:

Is it really that long? That's not that much to type.

If you want to use a framework, like MooTools or Prototype, they have an Element class, letting you do it in one line.

var opt = new Element('option', { value: day, text: day });

Solution 4:

The biggest problem with the document.createElement technique is that it's really SLOW. Using a framework is best, but either way, I'd suggest building the options list and setting the innerHTML property on the select box.

strOptions = "";
for (blah blah blah) 
{
    strOptions += '<option value="' + day + '">' + day + '</option>'
}
birthDay.innerHTML = strOptions;

The browser is going to be able to parse the HTML a lot faster than you'll be able to build these elements by hand.

In response to the comment, this is really why using a platform library is always worth it. In YUI3, I do this:

var fillSelectbox = function(select, optionList) {
    var i, option = '';
    for (i = 0; i < optionList.length; i += 1) {
        option += '<option value="' + optionList[i].Value + '" selected="' + (optionList[i].selected ? '"selected"' : '""') + '">' + optionList[i].Text + '</option>';
    }
    select.append(option);
    select.set('selectedIndex', -1);
};

Where select is the selectNode and optionList is a JavaScript array.

Post a Comment for "Shortcut For Document.createelement("option")?"