限制多个选择多个

时间:2015-07-25 13:15:44

标签: javascript php select

嗯伙计们请帮助我。我有3个选择倍数。我想限制每个选择倍数中的选定选项具有不同的限制。例如,在第一个选择上,我想将其限制为仅2个选定的选项。在第二个选择,我想仅限于4个选定的选项。在第三个选择,我想仅限于3个选定的选项。对不起。我是新的。请帮我。谢谢

// total option that can be selected for this should be 2
<select multiple class='qwerty' size = "3" style = "width:10%;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>

 // total option that can be selected for this should be 4
<select multiple class='qwerty' size = "3" style = "width:10%;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>

// total option that can be selected for this should be 3
<select multiple class='qwerty' size = "3" style = "width:10%;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>


                <script src="jquery.min.js"></script>
                    <script language = "JavaScript">
                        var last_valid_selection = null;
                        $('.qwerty').change(function(event) {
                            if ($(this).val().length > 2) {
                              alert('You can only choose 2!');
                              $(this).val(last_valid_selection);
                            } else {
                              last_valid_selection = $(this).val();
                            }
                         });
                    </script>
             </script>

1 个答案:

答案 0 :(得分:0)

您可以使用the data API来检索与该元素相关联的data-属性。我假设您编写的size属性用于此目的。

<select multiple class='qwerty' data-size="3" style="width:10%;">

每个last_valid_selection元素都需要隔离select。这可以通过创建捕获外部变量的闭包来实现。

<script src="jquery.min.js"></script>

<script type="text/javascript">
    $('.qwerty').change((function () {
        var last_valid_selection = null; // closure variable private to each of the select element
        return function(event) {
            var limit = parseInt($(this).data('size')); // data API to get the attribute data-size
            if ($(this).val().length > limit) {
                alert('You can only choose ' + limit + '!');
                $(this).val(last_valid_selection);
            } else {
                last_valid_selection = $(this).val();
            }
         };
    })());
</script>

有关示例,请参阅jsFiddle