按字母顺序排列的复选框组合的动态结果

Dynamic results from checkbox combinations in alphabetical order

我保证搜索了很多,但没有找到任何真正的答案。

我想根据选中的区域组合显示按字母顺序排列的国家/地区列表。到目前为止,我已经能够为单个区域实现这一点,但不能为组合实现。参见 https://jsfiddle.net/ro5yjg1c/ 我想要的是,例如,如果我单击 'Europe' 和 'Asia' 复选框,我希望在按字母顺序排列的连续列表中看到以下复选框: "Austria China Germany Japan Spain Thailand"。任何其他组合也需要起作用。这可能吗?

非常感谢任何帮助

<label>
<input type="checkbox" name="colorCheckbox" id="Europe" />Europe</label>
<label>
<input type="checkbox" name="colorCheckbox" id="Africa" />Africa</label>
<label>
<input type="checkbox" name="colorCheckbox" id="Asia" />Asia</label>


<div class="mywrapper">

<div id="myEurope">
<label>
  <input type="checkbox" value="Spain" />Spain</label>
<label>
  <input type="checkbox" value="Germany" />Germany</label>
<label>
  <input type="checkbox" value="Austria" />Austria</label>
</div>

<div id="myAfrica">
<label>
  <input type="checkbox" value="Nigeria" />Nigeria</label>
<label>
  <input type="checkbox" value="Egypt" />Egypt</label>
<label>
  <input type="checkbox" value="Kenya" />Kenya</label>
</div>

<div id="myAsia">
<label>
  <input type="checkbox" value="Thailand" />Thailand</label>
<label>
  <input type="checkbox" value="China" />China</label>
<label>
  <input type="checkbox" value="Japan" />Japan</label>
</div>

</div>



$(function() {
$('input[type="checkbox"]').click(function() {

var sortByText = function(a, b) {
return $.trim($(a).text()) > $.trim($(b).text()); 
}

// --------------
if ($(this).attr("id") == "Europe") {
var sorted = $('#myEurope label').sort(sortByText);
$('#myEurope').append(sorted);
$("#myEurope").slideToggle(200)
}
// --------------
if ($(this).attr("id") == "Africa") {
var sorted = $('#myAfrica label').sort(sortByText);
$('#myAfrica').append(sorted);
$("#myAfrica").slideToggle(200)
}
// --------------
if ($(this).attr("id") == "Asia") {
var sorted = $('#myAsia label').sort(sortByText);
$('#myAsia').append(sorted);
$("#myAsia").slideToggle(200)
}
// --------------

});
});



.mywrapper {
border: 1px solid blue;
height: 200px;
width: 300px;
border: 1px solid blue;
}

#myEurope {
display: none;
}

#myAfrica {
display: none;
}

#myAsia {
display: none;
}

您需要取消区域 div 中的元素分组(例如 remove ),以便它们出现在同一级别的数组中进行排序。您仍然可以对相关国家使用 css class 到 select 元素,只需将 css select 或从元素更改为 class:

.myEurope {
  display: none;
}

将 classes 应用于相关标签:

<label class="myEurope">
    <input type="checkbox" value="Spain" />Spain</label>
<label class="myEurope">
    <input type="checkbox" value="Germany" />Germany</label>

之后JS代码可以大大简化(见fiddle):

function sortByText(a, b) {
  return $.trim($(a).text()) > $.trim($(b).text());
}

// Pre-sort all the countries under mywrapper div (still keeping them hidden)
var li = $(".mywrapper").children("label").detach().sort(sortByText)
$(".mywrapper").append(li)

// On-click handler will just toggle display, countries already sorted
$('input[type="checkbox"]').click(function() {
 $('.my' + $(this).attr("id")).slideToggle(200)
})