How to enable/disable bootstrap selectpicker by ickeck checkbox

69,280

Solution 1

You should refresh the selectpicker once the change is done

here is a working fiddle

Code to refresh the UI is

$('.selectpicker').selectpicker('refresh');

for more information refer the DOCS

One more mistake i have found is, to disable you have to use

attr('disabled',true)

not

attr('disabled')

Solution 2

If your select picker has more than just a few options, the current accepted answer is incredibly slow. (can cause a hang around half a second, which is way too long to just make something disabled.)

This worked for me:

Disable:

$("#yourSelect").prop("disabled", true);
$(".selectpicker[data-id='yourSelect']").addClass("disabled");

Enable:

$("#yourSelect").prop("disabled", false);
$(".selectpicker[data-id='yourSelect']").removeClass("disabled");

This also has the added bonus of actually showing what the value of the select was when it was disabled. (which is the behavior of select boxes)

I'm kind of surprised the official documentation suggests to use refresh just to disable it, it takes way too long.

Solution 3

this is used to make disabled.

$('.selectpicker').prop('disabled', true);
$('.selectpicker').selectpicker('refresh');

this is to get it back

$('.selectpicker').prop('disabled', false);
$('.selectpicker').selectpicker('refresh');
Share:
69,280

Related videos on Youtube

user1896653
Author by

user1896653

Updated on March 24, 2021

Comments

  • user1896653
    user1896653 over 3 years

    There are selectpicker beside checkbox. I want if checkbox is checked, selectpicker will be enable, if unchecked, selectpicker will be disable. I wrote this which was not working ( Here is the fiddle ):

    $('.checkBox').on('ifChecked', function(event) {
        $(this).parents('.clearfix').find('.selectpicker').removeAttr('disabled');
    
    });
    $('.checkBox').on('ifUnchecked', function(event) {
        $(this).parents('.clearfix').find('.selectpicker').attr('disabled');
    });
    
  • Leith
    Leith about 7 years
    There's also a simple enable/disable example in the docs.
  • Patrick McDonald
    Patrick McDonald about 4 years
  • Meet Sinojia
    Meet Sinojia over 3 years
    I had a selectbox disabled (with selectpicker class), and I was enabling it using javascript, but it wasn't working (without selecpicker class, it was). All I needed was to refresh the selectpicker like you did. Thanks!
  • Juan R
    Juan R about 3 years
    $(".selectpicker").next("button").addClass("disabled");