Javascript - Working with the select dropdown box

javascript-dom

How can we obtain the value of the selected option?

Use the selectedIndex and the options attributes of the select element. For example:

var measureSetDropdownElement = document.getElementById('MeasureSetDropdown');
var measureSetSelectedOption = measureSetDropdownElement.options[measureSetDropdownElement.selectedIndex];
var measureSet = measureSetSelectedOption.value;

How can we iterate over the options within an HTML select dropdown box?

var selectElement = document.getElementById('...');
var options = selectElement.options;
var len = options.length;
var i, option, bestOption, text
for (i = 0; i < len; i++) {
    option = options[i];
}

How can we add option elements to a select elements?

var selectElement = document.getElementById('...');
selectElement.add(
  new Option('Two and \u00BD', '2.5'), $.browser.msid ? 2 : select.options[2]
);
var option = new Option(label, value);
if ($.browser.msie) {
  selectElement.add(option);
} else {
  selectElement.add(option,null);
}

If we have an option element object, how can we programmatically select it?

optionElement.selected = true;

Alternatively, we can use:

selectElement.selectedIndex = i

Notice that in the first example, we use optionElement, but in the second example, we use selectElement.

If we have an option element object, how can we determine its displayed text?

var displayedText = optionElement.text;

How can we scroll a particular option element to the top?

function scrollFacList(scrollToLetter) {
    var options = $('#facilityDropDown').get(0).options;
    var len = options.length;
    var i;
    var option;
    var bestOption;
    var text;
    var firstLetter;
    for (i = 0; i < len; i++) {
        option = options[i];
        text = option.text.toLowerCase();
        firstLetter = text.substr(0,1);
        if (firstLetter.charCodeAt(0) >= scrollToLetter.charCodeAt(0)) {
            bestOption = option;
            break;
        }
    }
    if (typeof(bestOption) != 'undefined') {
        var to = i * 18; // 18 is the estimated height for each option element.
        $('#facilityDropDown').scrollTop(to);
        bestOption.selected = true;
        $('#facilityDropDown').change();
    }
}

For the above function, given a letter, it will loop through the option elements, determine the best matched option element based on the first letter of the displayed text. If the best matched option is found, the variable i is known, and the variable 'to' is calculated, and then the jQuery scrollTop function is used to do the scrolling.

How can we filter a select dropdown box?

function facListFilter(filterBy) {
    var len = gFacList.length;
    var i;
    var optionList = '';
    for (i = 0; i < len; i++) {
        var fac = gFacList[i];
        var regex = new RegExp('^' + filterBy, 'i');
        if (fac.FACILITY_NAME.search(regex) > -1) {
            optionList = optionList + '<option value="' + fac.ENTITIESID + '">' + fac.FACILITY_NAME + '</option>';
        }
    }
    $('#facilityDropDown').html(optionList);
    var options = $('#facilityDropDown').get(0).options;
    options[0].selected = true;
    $('#facilityDropDown').change();
}

How can we appropriately change the text or label of an option element?

There are different ways to do this depending on the browsers being supported (not sure which way work best):

option.text = "...";
option.label = "...";
option.setAttribute("label","...");
option.innerHTML = "...";

How can we remove all the option elements from a select element?

this.options.length = 0;

What problem did I have working with the select element?

  1. When adding a new option to a select element, the new option element is not displayed. I still do not know the root cause of this problem (perhaps it has to do with whether we are using appropriate DOCTYPE or not, other HTML validation errors). To work around this problem:
    • I serialized all the option elements into a string, append the new option element as a string to this string, and use jQuery('id_of_the_select_element').html(html)
    • Use option.label = '…'
  2. In the same scenario as above, somehow IE add a colon to the value of the value attribute even though I construct the select element as an HTML string (valid HTML string), and then insert the select element into the DOM using innerHTML. I still do not know why IE behave like this (all version of IE). Perhaps this has to do with whether I use appropriate DOCTYPE or not, or other HTML validation errors. The work around is to use code to remove the extra colon. Instead of blaming IE, perhaps, I can also do a thorough check (search the code base to see if our code is adding the colon)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License