lundi 30 novembre 2020

jQuery triggering checkboxes and divs by prefix

I have a map that contains a number of regions with classes such as 'region-one', 'region-two' etc. Each of these have a corresponding checkbox with classes such as 'toggle-region-one', 'toggle-region-two'.

Clicking on each region or its checkbox will add an 'active' class. I achieve this with the below code:

$(function(){
  $("#toggle-region-one").change(function() {
    $("#region-one").toggleClass("active", this.checked)
  }).change();
});

$('#region-one').on('click', function() {
    $('#toggle-region-one').trigger('click');
});

I am adding more regions to the map and I do not want to repeat this same code again for each one. Is it possible to replace each class in the jquery so that it uses the prefixes "region-" and "toggle-" ?

So that when any region that starts with "region-" is clicked, the corresponding checkbox that begins with "toggle-" will also be checked?

I have also tried this but it selects all regions/checkboxes

$('div[id^="region-"]').on('click', function() {
    $('input:checkbox[id^=toggle-]').trigger('click');
});

$(function(){
  $('input:checkbox[id^=toggle-]').change(function() {
    $('div[id^="region-"]').toggleClass("active", this.checked)
  }).change();
});

I have set up a fiddle here https://jsfiddle.net/qvj6328m/1/




Aucun commentaire:

Enregistrer un commentaire