利用Jquery来计算元素的数量?

时间:2012-03-29 05:50:40

标签: jquery select

我想知道是否可以使用jquery来操纵我的“select”html元素:

我有三种不同的会员资格:Gold,Silver和PRemium,

因此Gold允许用户选择最多50个单词,而Silver允许用户选择最多10个单词。所以我想知道在用户选择10或50之后我是否可以禁用其余选项,具体取决于所选成员资格的类型。

这可能在JQuery中吗?似乎无法理解这种格式。

1 个答案:

答案 0 :(得分:2)

我们走了:

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery.min.js"></script>
    <script>
        $('document').ready(function () {
            var count;  // number of selected elements
            var type = "silver";  //lets assume the 'type' as silver and can select 3 elements

           $('#selectElem').bind('click', function (e)  {
                count = $('#selectElem :selected').length;
                switch (type) {
                case "gold":
                    //do somthing..
                    break;
                case "silver":
                    if(count >= 3) {
                        // disable the rest of the elems
                        $('#selectElem :not(:selected)').attr('disabled', 'disabled');
                    } else {
                        // remove disabled elems if any
                        $('#selectElem :not(:selected)').removeAttr('disabled');
                    }                
                    break;
                }
           });
        });    
    </script>
</head>

<body>
    <div>
        <select id="selectElem" multiple="multiple">
            <option value="1">One</option>
            <option value="2">Two</option>
            <option value="3">Three</option>
            <option value="4">Four</option>
            <option value="5">Five</option>
            <option value="6">Six</option>
            <option value="7">Seven</option>
        </select>
    </div>
</body>
</html>

示例:http://jsfiddle.net/kadaj/RRHCs/