如何在不禁用下拉列表更改的情况下对其进行限制 [英] How to restrict dropdown list change without disabling it

查看:89
本文介绍了如何在不禁用下拉列表更改的情况下对其进行限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不禁用下拉列表的情况下限制下拉列表选项的更改.
意味着我无法更改该选项,并且下拉列表不应为只读.
我的问题是我的服务器没有读取禁用的元素

How can i restrict a dropdown list option change without disabling that dropdownlist.
Means i can not change the option and that dropdownlist should not be readonly.
My problem is my server is not reading disabled elements

推荐答案

这是我的出价

jQuery

var lastSel = $('#foo').val();
$('#foo').change(function(){
    var $select = $(this), $status = $('#status');

    var $selOpt = $select.find('option:selected');
    if (!$selOpt.hasClass('disabled')){
        lastSel = $selOpt.index();
        $status.text('Selection changed to ' + $selOpt.val() + ' [' + lastSel + ']');
    }else{
        $selOpt.removeAttr('selected');
        $select.find('option:eq('+lastSel+')').attr('selected',true);
        $status.text('Invalid selection, reverting to ' + lastSel);
    }
});

HTML

<select id="foo">
    <option value="">Please select one</option>
    <option value="a">Option A</option>
    <option value="b">Option B</option>
    <option value="c" class="disabled">Option C</option>
    <option value="d">Option D</option>
    <option value="e">Option E</option>
    <option value="f" class="disabled">Option F</option>
    <option value="g">Option G</option>
    <option value="h">Option H</option>
    <option value="i" class="disabled">Option I</option>
</select>
<p id="status"></p>


插件版本

(function($){
    $.fn.extend({
        restrictedSelect: function(disabledClass){
            disabledClass = disabledClass || 'disabled';

            return this.each(function(i,e){
                var $s = $(e);

                // store the current selection. This is also used as a fall-back
                // value when the user selects something invalid.
                $s.data('currentSelection',$s.find('option:selected').index());

                $s.change(function(){
                    var $cs = $s.find('option:selected');
                    if ($cs.hasClass(disabledClass)){
                        $cs.removeAttr('selected');
                        $s.find('option:eq('+$s.data('currentSelection')+')').attr('selected',true);
                    }else{
                        $s.data('currentSelection',$cs.index());
                    }
                });
            });
        }
    });
})(jQuery);

$('select').restrictedSelect('invalid-select-option');

这篇关于如何在不禁用下拉列表更改的情况下对其进行限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆