Adding items in drop down list or list box using javascript
I have seen lots of questions in diffrent forums for adding items in drop down list or list box using javascript. Below is the script for the same.
<script type="text/javascript">
function AddItem(Text,Value)
{
// Create an Option object
var opt = document.createElement("option");
// Add an Option object to Drop Down/List Box
document.getElementById("DropDownList").options.add(opt);
// Assign text and value to Option object
opt.text = Text;
opt.value = Value;
}
<script />
You can use this function in for loop to add more than one item.
Getting the selected Value of dropdownlist using javascript
var roles = document.getElementById("DropDownList ");
if(roles!=null&& roles.selectedIndex!=-1){
//Getting value
rolesVal=roles.options[roles.selectedIndex].value;
//Getting text
rolesVal=roles.options[roles.selectedIndex].text;
}
Removing all the items of dropdownlist using javascript
var regions = document.getElementById("DropDownList ");
var len = regions.options.length;
for(i=len-1;i>=0;i--){
regions.options.remove(i);
}

本文介绍了如何使用JavaScript来添加、获取选中项以及移除下拉列表中的选项。通过具体的代码示例,展示了如何创建Option对象并将其添加到下拉列表中,如何获取所选项的值和文本,以及如何清除所有选项。
974

被折叠的 条评论
为什么被折叠?



