tuupola / jquery_chained

Chained Selects for jQuery and Zepto
https://appelsiini.net/projects/chained/
589 stars 283 forks source link

How to unchain chained dropdown? #36

Closed matriphe closed 10 years ago

matriphe commented 10 years ago

I've chained dropdown, and in some event, I want to unchain and rebind chain again? Here some example:

<select id="first">
<option value="a">A</option>
<option value="b">B</option>
</select>

<select id="second">
<option value="c" class="a">C</option>
<option value="d" class="a">D</option>
<option value="e" class="b">E</option>
</select>

<input type="checkbox" value="1" id="unchain" />

The Javascript will be:

$('#second').chained('#first');
$('#unchain').change(function(){
  if ($(this).prop('checked'))
  {
    // how to unchain the chained dropdown?
  }
});

Have tried $('#second').unbind('chained'); but didn't work.

Any suggestion?

tuupola commented 10 years ago

You can do $("#second").unbind("change");. Side effect is if you have other change events binded they will be unbinded too.

matriphe commented 10 years ago

@tuupola ah! didn't cross my mind! thanks! it's worked!

matriphe commented 10 years ago

Got answer from Stackoverflow here: http://stackoverflow.com/a/25912081/3460840

The complete script is:

$(function () {
    // remember #second select
    var secondCopy = $('#second').clone();
    $('#second').chained('#first');
    $('#unchain').change(function(){
        if ($(this).prop('checked')){
            $('#second').chained('#first');
        }
        else{
            $('#first').unbind('change');
            // remember selected value:
            var value = $('#second').val();
            // populate #second select with remembered options
            $('#second').html(secondCopy.html());
            // set saved value
            $('#second').val(value);
        }
    });
});