2014-10-01 59 views
0

我有一个代码,将下拉菜单中的项目添加到列表框中。当用户提交表单时,它通过列表框并选择所有项目,然后更新表格。JQuery检查空的列表框项目

如果用户从列表框中删除所有项目,我在代码中添加了一个空白项目添加到列表框,所以列表框仍然可以更新。我不得不这样做,因为如果在列表框中没有项目,那么它将不会被更新,并且旧项目将保留。

$.each(aListBoxes, function (idx, listBox) { 
    //If nothing in listbox add blank item so it can get updated 
    if ($("#" + listBox + " option").length < 1) { 
    ($("#" + listBox).append('<option value=""></option>')); 
    } 

现在,我想检查列表框中是否有多个项目,如果有的话删除这个空白项目,如果存在。

if ($("#" + listBox + " option").length > 1) { 
    $("#" + listBox + " option").each(function() { 

    //if item value is empty then remove 

整个至今脚本:

<script type="text/javascript"> 
    //for pre-selection of all elements in every list box 
    $(document).ready(function() { 
     var aListBoxes = []; 
     // get a list of all the listboxes on the form 
     $("[id*=" + "lbx" + "]:visible").each(function() { 
      aListBoxes.push(this.id); 
     }); 

     //on btnSubmit click because the form gets posted each time an autopostback field is hit. 
     $("input[name=btnSubmit]").click(function() { 
      //just before submission, go through each of the listboxes and if they contain anything, select everything. 
      $.each(aListBoxes, function (idx, listBox) { 
       //If nothing in listbox add blank item so it can get updated 
       if ($("#" + listBox + " option").length < 1) { 
        ($("#" + listBox).append('<option value=""></option>')); 
       } 
       //If more than 1 item check for blank and remove 
       if ($("#" + listBox + " option").length > 1) { 
        $("#" + listBox + " option").each(function() { 
         //if empty 
         //remove 
         }); 
       } 

       //select all before submitting 
       if ($("#" + listBox + " option").length > 0) { 
        $("#" + listBox + " option").each(function() { 
         $(this).prop('selected', 'selected') 
        }); 
       } 
      }); 
     }); 
    }); 
</script> 

回答

1

我希望通过空白选项,你的意思是它们的值是空的。试试这个: -

if ($("#" + listBox + " option").length > 1) { 
      $(this).each(function() { 
       if($(this).val()=="") 
        $(this).remove(); 
      }); 
    } 

,如果你的意思是文本是空的空白选项,然后写$(this).text()==""代替$(this).val()==""

+0

完美谢谢! – BringQBasicBack 2014-10-01 14:50:30

+0

您的欢迎。请接受,以便其他人也知道如果他们在寻找相同的答案。快乐编码! – 2014-10-01 14:51:25

0

jQuery的filter是专为这种类型的事情设计并避免使用each

if ($("#" + listBox + " option").length > 1) { 
     $(this).filter(function() { 
      return $(this).val()==""; 
     }).remove(); 
}