[javascript] js select 선택 / javascript select 선택 / 자바스크립트 select박스 선택
select 박스, 콤보박스라고도 부른다.
jquery로 제어하면 편하지만, 여기서는 순수 javascript로 제어하는 함수를 적어둔다.
// getComboSelectedId : select 태그의 아이디를 파라미터로 넘기면, 현재 선택되어 있는 인덱스를 반환한다.
function getComboSelectedId(_comboId) {
var comboObj = document.getElementById(_comboId);
if (comboObj == null) {
return null;
}
if (comboObj.options == null || comboObj.options.length == 0) {
return null;
}
var optionCount = comboObj.options.length;
for (var i=0; i<optionCount; i++) {
if (comboObj.options[i].selected) {
return comboObj.options[i].id;
}
}
return null;
}
// setComboToSelectOption : select 태그의 아이디와 option 태그의 아이디를 파라미터로 넘기면, 해당 option을 선택한다.
function setComboToSelectOption(_comboId, _itemId) {
var comboObj = document.getElementById(_comboId);
if (comboObj == null) {
return false;
}
if (comboObj.options == null || comboObj.options.length == 0) {
return false;
}
if (_itemId == null) {
_itemId = “”;
}
var optionCount = comboObj.options.length;
for (var i=0; i<optionCount; i++) {
if (comboObj.options[i].id == _itemId) {
comboObj.options[i].selected = true;
return true;
}
}
return false;
}