Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict dropdown list change without disabling it

Tags:

jquery

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

like image 259
Reddy Avatar asked Feb 24 '23 11:02

Reddy


1 Answers

Here's my bid

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>

Plug-in Version

(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');
like image 105
Brad Christie Avatar answered Mar 16 '23 01:03

Brad Christie