2012-08-29 121 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