Search code examples
javascriptjqueryhtmltwitter-bootstrapbootstrap-select

Chained dropdown with bootstrap selectpicker not working


I am using Bootstrap-select - Silvio Moreto and having two drop-down options.

<strong>Option 1</strong>
<select class="selectpicker" name="number">
    <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>
</select>
<br />

<strong>Option 2</strong>
<select class="selectpicker" name="abc">
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
    <option value="5">E</option>
</select>

and jQuery code is:

$('.selectpicker').selectpicker({
     style: 'btn-info',
     size: 4
});

Now what I am trying is:

  • If user select 3 from First Option, I want to set C value selected from Second Option and same reverse method with Second Option is used.
  • If user select C from Second Option, I want to set 3 value selected from First Option.

I have wrote bellow jQuery code and it is working with only First Option but not with Second Option.

$('.selectpicker').on('change', function () {
    var opValue = $('.selectpicker').val();
    $('.selectpicker').val(opValue);
    $('.selectpicker').selectpicker('refresh');
});

NOTE: In my example value will be same and it will be not change.

Here is JSFiddle sample code: http://jsfiddle.net/user/mananpatel/

Any idea how to do it?

Thanks.


Solution

  • Here you go:

     $('.selectpicker').selectpicker({
         style: 'btn-info',
         size: 4
     });
    
     $('.selectpicker').on('change', function () {
         var opValue = $(this).val();
         console.log(opValue);
         $('.selectpicker').val(opValue);
         $('.selectpicker').selectpicker('refresh');
     });
    

    Use $(this) to get the value of the selected combo. In your code you are always using the value of the first combo.

    Fiddle : http://jsfiddle.net/RUAS4/126/