skip to Main Content

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.

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. .closest()

    testing the element itself and traversing up through its ancestors in the DOM tree

    In you example

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

    you can change

    var aid = $(this).closest("div.aid_closest").find("input[name='aid']").val();
    

    to

    var aid = $(this).closest("div").find("input[name='aid']").val();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search