2012-08-29 126 views
0

我使用取决于多重选择框的值,这个填充列表:追加列表项目计数的jQuery

$(document).ready(function() { 
    $("select").change(function() { // <-- bind change event handler to the drop downs 
     var sel = ""; 
     $(".option-select option:selected").each(function() { // <-- then iterate each time it changes 
      if ($(this).index() !== 0) { // <-- only if not default 
       sel += "<li>" + $(this).text() + "</li>"; 
      } 
      $("ul.result ul").empty().append(sel); //<-- empty() to remove old list and update with new list 
     }); 
    }); 
});​ 

然而,我无法弄清楚如何打印添加到列表选项的数量,或选择数值的选择框的数量。我需要告诉用户他们已经选择了多少选项,并显示像我已经有的选项。我已经找到了如何使用列表中的项目数量:

var count = $("ul li").length; 

但无法弄清楚如何打印此计数。

回答

0

能做到这样

$(document).ready(function() { 
    $("select").change(function() { // <-- bind change event handler to the drop downs 
     var sel = ""; 
     var counter = 0; 
     $(".option-select option:selected").each(function() { // <-- then iterate each time it changes 
      if ($(this).index() !== 0) { // <-- only if not default 
      { 
       sel += "<li>" + $(this).text() + "</li>"; 
       counter++; 
      } 
      }  
      $("ul.result ul").empty().append(sel); //<-- empty() to remove old list and update with new list 
     }); 
    }); 

//The Number of Option's Added 
counter; 

或只是转换enter code here SEL jQuery的

$(sel).length; 
0

我会做的元素,并把价值在里面,是这样的:

<div id="count_holder">You have <span></span> options</div> 
<script> 
    $("#count_holder").find("span").text(count); 
</script> 
0

可能你想要这样的东西

$(document).ready(function() { 
    $("select").change(function() { 
     var list=$(this).children(':selected').not($(this).children()[0]); 
     $('#result, #count').empty(); 
     if(list.length){ 
      list.each(function(){ 
       $('<li></li>').val($(this).val()).text($(this).text()) 
       .appendTo($('#result')); 
       $('#count').html(list.length); 
      }); 
     } 
    }); 
}); 

DEMO