简体   繁体   English

使用jQuery获取选定项计数ListBox

[英]Getting selected items count ListBox with jQuery

As in topic - how to get selected items count in ListBox with jQuery, while user is selecting new item? 就像在主题中一样-当用户选择新项目时,如何使用jQuery在ListBox中获取所选项目?

I have these code: 我有以下代码:

@Html.ListBoxFor(x => Model.StatesID, Model.States,
        new { @class = "chzn-select", @id="StatesID", data_placeholder = "Choose...", style = "width:350px;" })


function countStates() {
    var count = $("#StatesID:selected").length;
    alert(count);

}

I can get count of selected items in onclick input action, but how to connect this js function with onclick event, or maybe other event, when user is selecting new item in my listbox? 我可以在onclick输入操作中获得选定项目的计数,但是当用户在列表框中选择新项目时,如何将该js函数与onclick事件或其他事件连接起来?

Adding my comment as answer.... 添加我的评论作为答案...。

If it is a multi-select, you will want to use.... 如果是多选,则需要使用...。

$('#StatesID').on('change', function(){
    countStates();
});

otherwise click does not fire if the user selects more that one option at a time. 否则,如果用户一次选择多个选项,则单击不会触发。

Try this : 尝试这个 :

$(document).ready(function() {
    $('#StatesID').click(countStates);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM