im trying to get the closest id whena button is clicked to send it in an ajax request. But ive been struggling achiving so.
The HTML part is this one (cshtml)
<div id="[email protected]" >
<!--Delete car button-->
<div>
<button type="button" id="btnDeleteCar" name="btnDeleteCar">
<i ></i>
</button>
</div>
</div>
im trying to extract the @car.Id part
The JS part is this:
id: $(this).closest("div").find(".modifyCar").attr("id"),
CodePudding user response:
Consider the following.
$(function() {
$(".btn").click(function() {
var myId = $(this).closest(".modifyCar").attr("id");
console.log(myId);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="[email protected]" >
<!--Delete car button-->
<div>
<button type="button" id="btnDeleteCar" name="btnDeleteCar"><i ></i></button>
</div>
</div>
.closest()
can accept a selector, like a Class name. Your Code will stop at the Parent DIV Element, as that matches the closest "div"
selector.