0

I'm using a plugin that creates a span class element based on a label I've defined in a separate javascript file. I want to create an eventListener for when the checkbox has been checked and reference the text in the span class using jQuery. However, I am not sure on how to reference the span class for each label class #leaflet-layerstree-header-label input.

Something like an example here that adds a map function to obtain the collection.

The element for each label is referenced as such:

<label class="layerstree-header-label">
  <input type="checkbox" class="control-layers-selector">
  <span class="layerstree-header-name">7211</span>
</label>
Ciara Spencer
  • 111
  • 2
  • 11
  • how do you want the text? lets say each time some one clicks the checkbox, you need all the texts of span in an array or something else – Tushar Gupta Apr 09 '23 at 00:57
  • @Tushar I'm going to take the selections and use them as parameters in a separate request module to be called upon selection. – Ciara Spencer Apr 11 '23 at 18:04

2 Answers2

1

You can attach the event listener on change event for the checkbox and use .siblings to find the span

$(".control-layers-selector").on("change", function(e) {
  if ($(this).is(':checked'))
    console.log($(this).siblings('span').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="layerstree-header-label">
  <input type="checkbox" class="control-layers-selector">
  <span class="layerstree-header-name">7211</span>
</label>

<label class="layerstree-header-label">
  <input type="checkbox" class="control-layers-selector">
  <span class="layerstree-header-name">9090</span>
</label>

<label class="layerstree-header-label">
  <input type="checkbox" class="control-layers-selector">
  <span class="layerstree-header-name">9090</span>
</label>
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
  • This doesn't seem to be working (i.e. no output to console with selections) - I believe I have to reference the [module](https://github.com/jjimenezshaw/Leaflet.Control.Layers.Tree/blob/master/L.Control.Layers.Tree.js) itself somehow as there are multiple child layers and class inheritances from which it spans. – Ciara Spencer Apr 11 '23 at 17:42
  • I cant see your full code, so you need to check your object reference yourself – Tushar Gupta Apr 12 '23 at 00:24
0

So I figured out I have to reference the container for the module in order to obtain the text for the selection. The solution that worked was as follows (with contribution from @Tushar):

var layerControl = L.control.layers.tree (baseMaps, overlaysTree, {
  collapsed: false
})

var htmlObject = layerControl.getContainer().querySelectorAll('input');

$(htmlObject).on("change", function(e) {
  if ($(this).is(':checked'))
    console.log($(this).siblings('span').text());
});
Ciara Spencer
  • 111
  • 2
  • 11