Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get previous element not working as expected [duplicate]

I am using jQuery to try and get the closest previous element like this when a checkbox is selected...

jQuery( document ).ready(function() {

    jQuery(".input1").change(function() {
    
      var myinput = jQuery(this).closest(".myinput");
  		console.log(myinput);

    });  
          
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <td>
    <div class="element1">
      <input class="myinput">
    </div>
  </td>
  <td>
    <div class="element2">
    </div>
  </td>
  <td>
    <div class="element3">
    <input type="checkbox" class="input1">
    </div>
  </td>
</table>

When the checkbox is clicked it gives me the original clicked element int he console log instead of the myinput element.

Where am I going wrong?

like image 807
fightstarr20 Avatar asked Nov 24 '25 10:11

fightstarr20


1 Answers

Try this, get the parent table and then the closest input. After adding the .closest('table') selector the console.log shows the matched input

jQuery( document ).ready(function() {

    jQuery(".input1").change(function() {
      var myinput = 
        jQuery(this).closest('table').find(".myinput");
        console.log(myinput);

    });  
          
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <td>
    <div class="element1">
      <input class="myinput">
    </div>
  </td>
  <td>
    <div class="element2">
    </div>
  </td>
  <td>
    <div class="element3">
    <input type="checkbox" class="input1">
    </div>
  </td>
</table>
like image 71
ppollono Avatar answered Nov 27 '25 00:11

ppollono



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!