Javascript操作selectコントロール大全書(出所:オンライン抜粋)

4494 ワード


Javascript select ( 、 、 、 、 、 )
Posted on 2007-08-08 14:56 (6036) (16) : JavaScript
1 select Value="paraValue" Item
2 select Item
3 select Item
4 select
5 select value="paraValue" text "paraText"
6 select text="paraText" Item
7 select value="paraValue" Item
8 select value
9 select text
10 select Index
11 select

js
// 1. select Value="paraValue" Item
function jsSelectIsExitItem(objSelect, objItemValue) {
var isExit = false;
for (var i = 0; i < objSelect.options.length; i++) {
if (objSelect.options[i].value == objItemValue) {
isExit = true;
break;
}
}
return isExit;
}

// 2. select Item
function jsAddItemToSelect(objSelect, objItemText, objItemValue) {
//
if (jsSelectIsExitItem(objSelect, objItemValue)) {
alert(" Item Value ");
} else {
var varItem = new Option(objItemText, objItemValue);
objSelect.options.add(varItem);
alert(" ");
}
}

// 3. select Item
function jsRemoveItemFromSelect(objSelect, objItemValue) {
//
if (jsSelectIsExitItem(objSelect, objItemValue)) {
for (var i = 0; i < objSelect.options.length; i++) {
if (objSelect.options[i].value == objItemValue) {
objSelect.options.remove(i);
break;
}
}
alert(" ");
} else {
alert(" select ");
}
}


// 4. select
function jsRemoveSelectedItemFromSelect(objSelect) {
var length = objSelect.options.length - 1;
for(var i = length; i >= 0; i--){
if(objSelect[i].selected == true){
objSelect.options[i] = null;
}
}
}

// 5. select value="paraValue" text "paraText"
function jsUpdateItemToSelect(objSelect, objItemText, objItemValue) {
//
if (jsSelectIsExitItem(objSelect, objItemValue)) {
for (var i = 0; i < objSelect.options.length; i++) {
if (objSelect.options[i].value == objItemValue) {
objSelect.options[i].text = objItemText;
break;
}
}
alert(" ");
} else {
alert(" select ");
}
}

// 6. select text="paraText" Item
function jsSelectItemByValue(objSelect, objItemText) {
//
var isExit = false;
for (var i = 0; i < objSelect.options.length; i++) {
if (objSelect.options[i].text == objItemText) {
objSelect.options[i].selected = true;
isExit = true;
break;
}
}
//Show
if (isExit) {
alert(" ");
} else {
alert(" select ");
}
}

// 7. select value="paraValue" Item
document.all.objSelect.value = objItemValue;

// 8. select value
var currSelectValue = document.all.objSelect.value;

// 9. select text
var currSelectText = document.all.objSelect.options[document.all.objSelect.selectedIndex].text;

// 10. select Index
var currSelectIndex = document.all.objSelect.selectedIndex;

// 11. select
document.all.objSelect.options.length = 0;