2012-10-15 59 views
0

当我点击按钮(复选框)时,列表框中的所有项目都将消失。如何防止此操作?我的删除功能无法正常工作。是因为我的javascript?我的代码如下:删除列表框中的项目无法正常工作

.aspx文件

    <tr> 
         <td width="150px"> 
          <asp:TextBox ID="TextBox1" runat="server" onkeypress="displayKeyCode_demo(event)"></asp:TextBox>   
         </td> 
         <td width="200px"> 
<asp:ListBox ID="LstScan" runat="server" Height="200px" Width="150px" > 
          </asp:ListBox> 

          <asp:HiddenField runat="server" ID="hdnScan"/> 
         </td> 

         <td width="100px"> 
          <asp:Button ID="Button2" runat="server" Text="Remove" OnClientClick="removeItem()" /> 
         </td></tr></table> 






javascript: 

    <script type="text/javascript"> 
      function displayKeyCode_demo(e) { 
       var code; 
       if (!e) var e = window.event; 
       if (e.keyCode) code = e.keyCode; 
       else if (e.which) code = e.which; 
       if (code == 13) { 

        var ListBox = document.getElementById("<%=LstScan.ClientID%>"); 
        var TextBox = document.getElementById("<%=TextBox1.ClientID%>"); 
        var hdnScan = document.getElementById("<%=hdnScan.ClientID%>"); 
       var myOption = new Option(); 
       myOption.text = document.getElementById("<%=TextBox1.ClientID%>").value.trim(); //Textbox's value 
       myOption.value = document.getElementById("<%=TextBox1.ClientID%>").value.trim(); //Textbox's value 
       hdnScan.value = hdnScan.value + "," + TextBox.value; 
       ListBox.appendChild(myOption); 
       document.getElementById("<%=TextBox1.ClientID%>").value = ''; 

//    e.preventDefault(); 
      } 
     } 
     function removeItem() { 
//   var i; 
//   var selectbox = document.getElementById("<%=LstScan.ClientID%>"); 
//   for (i = selectbox.options.length - 1; i >= 0; i--) { 
//    if (selectbox.options[i].selected) 
//     selectbox.remove(i); 
      //   } 
      document.getElementById("<%=LstScan.ClientID%>").options[document.getElementById("<%=LstScan.ClientID%>").selectedIndex] = null; 
     } 

回答

0

您可以使用此代码

function removeItem() 
{ 
    document.getElementById('<% = LstScan.ClientID %>').options.length = 0; 
} 
+0

我认为主要的问题不是'removeItem'不工作,而是_“列表框中的所有项目都消失了”_在回发上,这是在客户端上创建元素时正常的。 –

+0

如何在回发列表框中保留值。 – user1737502

0

使用jQuer尝试Y:

要删除所有选项:

$('<%=LstScan.ClientID%>').empty(); 

参考 - .empty()

要删除特定选项:

$('OPTION[VALUE="valueofOption"]', $("<%=LstScan.ClientID%>")).remove(); 

参考 - .remove()

+0

使用javascript的Iam – user1737502