Get specific id of span

Viewed 48

so I need to get id of span where is input of checkbox.. so if checkbox is checked I need to get specific id of span where is that checked checkbox.

my code

HTML:

<div id="APs">
    <span id="59" name="4"><input type="checkbox"> <b>[Site: 4 | ID: 59]</b> - something<br></span>
    <span id="60" name="4"><input type="checkbox"> <b>[Site: 4 | ID: 60]</b> - something<br></span>
    <span id="275" name="4"><input type="checkbox"> <b>[Site: 4 | ID: 275]</b> - something<br></span>
    <span id="2903" name="4"><input type="checkbox"> <b>[Site: 4 | ID: 2903]</b> - something<br></span>
    <span id="3417" name="4"><input type="checkbox"> <b>[Site: 4 | ID: 3417]</b> - something<br></span>
</div>

jQuery:

$(document).on("change", ":checkbox", function () {
   if ($(this).is(":checked")) 
   {
      const apid = $("#APs span").attr("id");
      console.log(apid);

      //another lines of code

   }
}

This code only choose only first span even if I click on second checkbox it will still log id 59.

I need to get that id because I am getting datas from JSON what is on url but I need that id to get right data.

1 Answers

The issue is because you select all #APs span elements, not the one related to the checkbox which was selected. When you call jQuery's attr() method on an object containing a collection it will only read the property from the first element.

To change this behaviour, use the this keyword along with the closest() selector to get the parent span of the checkbox which raised the change event.

$(document).on("change", ":checkbox", function() {
  let $cb = $(this);
  if ($cb.is(":checked")) {
    const apid = $cb.closest('span').prop("id");
    console.log(apid);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="APs">
  <span id="59" name="4"><input type="checkbox"> <b>[Site: 4 | ID: 59]</b> - something<br></span>
  <span id="60" name="4"><input type="checkbox"> <b>[Site: 4 | ID: 60]</b> - something<br></span>
  <span id="275" name="4"><input type="checkbox"> <b>[Site: 4 | ID: 275]</b> - something<br></span>
  <span id="2903" name="4"><input type="checkbox"> <b>[Site: 4 | ID: 2903]</b> - something<br></span>
  <span id="3417" name="4"><input type="checkbox"> <b>[Site: 4 | ID: 3417]</b> - something<br></span>
</div>

Related