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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With