Monday, December 28, 2009

Set value to a combobox - Javascript

/***********************************************************************************
@Author : Karthikeyan A
@Purpose : To set a particular value to a combo box, Provided the value is one of its options
@Type : Function
@Name : setComboValue
@Param : comboBoxId, ID of the combo box element
@Param : ValueToSet, The value to be set to the combo box
***********************************************************************************/
function setComboValue(comboBoxId,valueToSet){
var cmbElement=document.getElementById(comboBoxId);
if((typeof cmbElement=='undefined') || (cmbElement==null) || (typeof valueToSet=='undefined')) {
throw new Error('No element with id "'+ comboBoxId + '" is found <br> - in function getComboValue(comboBoxID)');
}
var cmbItr;
try {
for (cmbItr=0;cmbItr<cmbElement.options.length;cmbItr++) {
var currValue=document.all?cmbElement.options[cmbItr].text:cmbElement.options[cmbItr].value;
if (currValue==valueToSet) {
cmbElement.options.selectedIndex=cmbItr;
}
}
} catch(notCombobox) {
try {
cmbElement.value=valueToSet;
} catch (notFieldElement) {
throw new Error("The element corresponding to the id:\""+ comboBoxID+"\""+
" is neither a Combo Box, nor an Input Field or does not exist"+
"<br> - in function getComboValue(comboBoxID)");
}
}
}

No comments:

Post a Comment