按字母顺序从复选框组合中获得动态结果

Dynamic results from checkbox combinations in alphabetical order

本文关键字:动态 结果 组合 复选框 顺序      更新时间:2023-09-26

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

我想根据选中地区的组合显示按字母顺序排列的国家列表。到目前为止,我已经能够为单个区域实现这一点,但不能为组合。参见https://jsfiddle.net/ro5yjg1c/我想要的是,如果,例如,我点击"欧洲"answers"亚洲"复选框,我希望看到以下复选框在一个连续的字母顺序列表:"奥地利中国德国日本西班牙泰国"。任何其他组合也需要起作用。这可能吗?

任何帮助都非常感谢

<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来选择元素,只需将css selector从element更改为class:

.myEurope {
  display: none;
}

将类应用于相关标签:

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

之后,JS代码可以显著简化(见小提琴):

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)
})