Wednesday, February 11, 2009

Javascript HTML Select Again

Just a short follow up to yesterday's post with set value and get value functions that will work with both single and multiple select HTML elements. The code expects that you will correctly pass a single value / array value when calling against the select element:

function indexOf(array, value) {
for (var i = 0, l = array.length; i < l; ++i) {
if (array[i] === value) return i;
}
return -1;
}
function getSelectIndexByValue(select, value) {
var options = select.options;
for (var i = 0; i < options.length; i++) {
if (options[i].value == value) return i;
}
return -1;
}
function setSelectedByValue(select, value, invert) {
if (select.multiple) {
invert = invert || false;
var options = select.options;
for (var i = 0, l = options.length; i < l; ++i) {
var option = options[i];
option.selected = (indexOf(value, option.value) === -1) === invert;
}
} else {
select.selectedIndex = getSelectIndexByValue(select, value);
}
}
function getSelectValue(select) {
var result;
if (select.multiple) {
result = [];
var options = select.options;
for (var i = 0, l = options.length; i < l; ++i) {
var option = options[i];
if (option.selected) result.push(option.value);
}
} else {
result = select.value;
}
return result;
}
view raw gistfile1.js hosted with ❤ by GitHub


Probably only the set part of this code is of interest to you if you are using Prototype as prototype will give you the correct result with Form.element.getValue or $F.