jQuery Chained: How to unchain chained dropdown?

会有一股神秘感。 提交于 2020-01-03 03:00:10

问题


I used this plugin: https://github.com/tuupola/jquery_chained

I've chained dropdown, and in some event, I want to unchain and rebind chain based on the event.

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?


回答1:


Chained plugin filters all non-matching options from #second select, so when you "unchain" (unbind from change event), the #second select will have some options cut off (i.e. lost forever).

It can only work if after unchaining you would reinitialize #second select with full set of options. So something like this should be done:

$(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);
        }
    });
});

Demo.



来源:https://stackoverflow.com/questions/25908781/jquery-chained-how-to-unchain-chained-dropdown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!