I want to load the "select" dropdown values dynamically. That is I am getting the values of dropdown from the data base. How to set the set it dynamically?
Created May 7, 2012
The Option object is created using the word new
myOption= new Option();
the text and the value of the Option object is set just like below
myOption.text="option text here";
The option can be inserted into selection defining the option index number. Below the option is inserted at the end of a selection
document.formName.selectName.options[document.formName.selectName.options.length]=myOption;
The option can be deleted just setting the option to null
document.formName.selectName.options[1]=null; --> the second option is deleted.
Take a look at the brief example below to make sure about how the things are going.
--------------------------------------------------
Enter the text of the new option here:
Enter the value of the new option here:
<input type="button" value="Insert new option" onclick="insertNewOption();">
<input type="button" value="Change the selected option" onclick="insertNewOption();">
<hr>
This button deletes the selected option or the last option
<input type="button" value="Delete Option" onclick="deleteOption();">
<hr>
This button deletes all of the options
<input type="button" value="Delete all options" onclick="deleteOptions();">
</form>
</body>
</html>
--------------------------------------------------
myOption.value="option value here";
<html>
<head>
<title>Untitled</title>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
function insertNewOption()
{
myOption=new Option();
myOption.text=document.selectionForm.textinsert.value;
myOption.value=document.selectionForm.valueinsert.value;
if (document.selectionForm.dynamicSelection.selectedIndex>0)
insertIndex=document.selectionForm.dynamicSelection.selectedIndex;
else
insertIndex=document.selectionForm.dynamicSelection.options.length;
document.selectionForm.dynamicSelection.options[insertIndex]=myOption;
}
function deleteOption()
{
if (document.selectionForm.dynamicSelection.selectedIndex>0)
deleteIndex=document.selectionForm.dynamicSelection.selectedIndex;
else
deleteIndex=document.selectionForm.dynamicSelection.options.length-1;
document.selectionForm.dynamicSelection.options[deleteIndex]=null;
}
function deleteOptions()
{
while (document.selectionForm.dynamicSelection.options.length>0)
{
deleteIndex=document.selectionForm.dynamicSelection.options.length-1;
document.selectionForm.dynamicSelection.options[deleteIndex]=null;
}
}
</SCRIPT>
</head>
<body>
<form name="selectionForm">
<select name="dynamicSelection">
</select>
<input type="text" name="textinsert" size="30">
<input type="text" name="valueinsert" size="30">