dimanche 6 novembre 2016

Exclude items from part of checkbox list before sorting

Can't believe I'm stuck on this! The JS fiddle http://ift.tt/2fesX8e shows countries appearing, in alphabetical order, from any combination of the 3 regional checkbox selections. In the future I will want to restrict the scope of the country list using an instruction in the JS code. For example, even with all 3 checkboxes ticked, I might want the code to exclude all Asian countries from appearing, but maintain the alphabetical order for the remaining countries being shown. I've tried using .filter() and .detach() and .remove(), as suggested in previous posts, but am unable to get anything to work.

Can anyone suggest how I can add a small modification to the JS code so I can exclude the countries from 1 or 2 regions from being displayed? Ideally I don't want to restructure the HTML. Thanks

<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">

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

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

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

</div>





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

var li = $(".mywrapper").children("label").detach().sort(sortByText)
$(".mywrapper").append(li)

$('input[type="checkbox"]').click(function() {
$('.my' + $(this).attr("id")).slideToggle(200)
})




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

.myEurope {
display: none;
}

.myAfrica {
display: none;
}

.myAsia {
display: none;
}




Aucun commentaire:

Enregistrer un commentaire