删除下拉列表中的空白选项

时间:2011-11-24 06:22:31

标签: javascript html drop-down-menu

我有一个下拉列表,我通过javascript动态创建。在蓝色的一个空白选项被添加到第0个位置。现在我想通过javascript删除这个空白选项。我面临的唯一路障是检查空白选项。请帮忙

1 个答案:

答案 0 :(得分:2)

<title>Dynamic DropDownList</title>

<script type="text/javascript" language="javascript">



function AddItemInList()

{

    var list =  document.getElementById('DropDownList1');

    var box =  document.getElementById('Text1');

    var newListItem = document.createElement('OPTION');



    newListItem.text = box.value;

    newListItem.value = box.value;

    list.add(newListItem);



    box.value = "";

    box.focus(); 



}

function RemoveItemInList()

{

    var list  = document.getElementById('DropDownList1');

    if(list.options.length > 0)

    {

        for(var i = list.options.length - 1; i >= 0; i--)

        {

            if(list.options[i].selected)

            {

                list.remove(i);

                return false;

            }

        }

    }

    else

    {

        alert('Unable to remove. List is Empty!');

    }



}



</script>

<form id="form1" runat="server">

<div>

    <asp:DropDownList ID="DropDownList1" runat="server">

    </asp:DropDownList>

    <input id="Text1" type="text" />

    <input id="Button1" type="button" value="Add New"  onclick="AddItemInList();"/>

    <input id="Button2" type="button" value="Remove Item"  onclick="return RemoveItemInList();"/>

</div>

</form>