已选择项目的Jquery计数选择框

FMK*_*FMK 2 javascript jquery

我想知道是否有更有效的方法来计算用户的选择:

这是页面上多次选择下拉列表:

<select class="span2 jquery-countable" name="category[7]">
    <option></option>
    <option value="1">1. vote</option>
    <option value="2">2. vote</option>
    <option value="3">3. vote</option>
    <option value="4">4. vote</option>
</select>
Run Code Online (Sandbox Code Playgroud)

这是我的js计算选择:

$(document).ready(function () {

    $('#selected-count').html('You choose ' + getCount() + ' entries');

    function getCount() {
        prio1 = $('.jquery-countable option:selected[value="1"]').length;
        prio2 = $('.jquery-countable option:selected[value="2"]').length;
        prio3 = $('.jquery-countable option:selected[value="3"]').length;
        prio4 = $('.jquery-countable option:selected[value="4"]').length;

        return prio1 + prio2 + prio3 + prio4;
    }

    $('.jquery-countable').change(function () {
        $('.jquery-countable option:selected').each(function () {
            $('#selected-count').html('You choose ' + getCount() + ' entries');
        })
    })
});
Run Code Online (Sandbox Code Playgroud)

我的目标是计算用户所做的非空的所有选择?!

有更有效的方法吗?

谢谢!

pap*_*tis 7

这将返回您希望的非空的所选项目数:

function getCount(){
   return $("select.jquery-countable option:selected[value!='']").length;
}
Run Code Online (Sandbox Code Playgroud)