Grab ID of clicked element

Asked

Viewed 4,998 times

2

I have a DIV and this DIV has some checkbox with ID and I want to know how I get the checkbox id clicked.

<div>
    <input type="checkbox" id="0" value="false" name="ckb0">
    <label for="0">TESTE</label>
</div>
<div>
    <input type="checkbox" id="1" value="false" name="ckb1">
    <label for="1">Posso escolher essa</label>
</div>
<div>
    <input type="checkbox" id="2" value="false" name="ckb2">
    <label for="2">Essa também</label>
</div>
<div>
    <input type="checkbox" id="3" value="false" name="ckb3">
    <label for="3">E essa</label>
</div>
<div>
    <input type="checkbox" id="4" value="false" name="ckb4">
    <label for="4">este tambem</label>
</div>

1 answer

3


Create a event handler and use $(this).attr("id"). The code below will catch clicks on all checkbox within the div #resposta:

$(document).ready(function(){
   $("#resposta").find("input[type='checkbox']").click(function(){
      console.log($(this).attr("id"));
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resposta" class="box-resposta">
   <div>
      <input type="checkbox" id="0" value="false" name="ckb0">
      <label for="0">TESTE</label>
   </div>
   <div>
      <input type="checkbox" id="1" value="false" name="ckb1">
      <label for="1">Posso escolher essa</label>
   </div>
   <div>
      <input type="checkbox" id="2" value="false" name="ckb2">
      <label for="2">Essa também</label>
   </div>
   <div>
      <input type="checkbox" id="3" value="false" name="ckb3">
      <label for="3">E essa</label>
   </div>
   <div>
      <input type="checkbox" id="4" value="false" name="ckb4">
      <label for="4">este tambem</label>
   </div>
</div>

Documentation jQuery:

Function . attr()
Function . find()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.