Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 已选择项的Jquery计数选择框_Javascript_Jquery - Fatal编程技术网

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

Javascript 已选择项的Jquery计数选择框,javascript,jquery,Javascript,Jquery,我想知道是否有更有效的方法来计算用户的选择: 这是页面上多次出现的选择下拉列表: <select class="span2 jquery-countable" name="category[7]"> <option></option> <option value="1">1. vote</option> <option value="2">2. vote</option> <

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

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

<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>
我的目标是统计用户做出的所有非空选择

有没有更有效的方法


谢谢

是的,把[value=#]去掉就行了。更通用的选择器将返回所选值的数组,在select的情况下,该数组应仅包含1

function getCount() {
    return $('.jquery-countable option:selected').length;
}

这将统计页面上使用jquery countable类选择的“已选”选项的总数。

这将返回所选项目的数量,这些项目并非如您所愿为空:

function getCount(){
   return $("select.jquery-countable option:selected[value!='']").length;
}
这里有一个方法

$(document).ready(function () {

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



    $('.jquery-countable').change(function () {
        var count = 0;
        $('.jquery-countable').each(function () {
            if($.trim($(this).val()).length > 0)
                count++;
        });
        $('#selected-count').html('You choose ' +count + ' entries');
    })
});​

试试这样的方法

$("select").change(function(){           
   var count = $("select.jquery-countable option:selected[value!='']").length;
   console.log(count);
});

console.log($('.jquery countable option:selected')我已经尝试过了,但它也返回空的
选择。在我的测试用例中,有22个选择,如果我只选择其中的10个,它仍然返回22个“selected”。您还需要console.log($(($)select.jquery-countable option:selected[value!=''))。length)
$("select").change(function(){           
   var count = $("select.jquery-countable option:selected[value!='']").length;
   console.log(count);
});