问题
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