javascripthtmljqueryclosest

How to find the value of input field using jquery .closest() method when checkbox is checked?


This code is giving me undefined value when I try to show the value through alert message.

<div>
  <input type="checkbox">   
  <div class="aid_closest"> 
       <input type="text" name="aid" id="aid" class="aid" value="sample_value"> 
  </div>
</div>

And this is what I put inside my script code..

<script src="https://code.jquery.com/jquery-3.6.0.min.js" ></script>
<script>
$('input[type="checkbox"]').click(function(){
  var aid = $(this).closest("div.aid_closest").find("input[name='aid']").val();
  
  if($(this).is(":checked")){
    alert(aid);
  }
});
</script>

I'd appreciate all the help and suggestion you will give to me.


Solution

  • you can use next jQuery function.

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" ></script>
    <script>
    $('input[type="checkbox"]').click(function(){
       var aid = $(this).next('.aid_closest').find("input[name='aid']").val();
    
       if($(this).is(":checked")){
           alert(aid);
       }
    });
    </script>