when i click on 'customer-row' it should add class 'open-carrier-tiers' in 'carrier-tiers'. which is working. but when i click on 'carrier-tiers-close-btn' then it should remove the same class that added before from its parent parent element. which is not working. and i am using $(this) because this whole code repeating multiple time on page.
<tr >
<td >
<div >
<li >close</li>
<form action="" method="POST">
<input type="text" name="Customer Name">
<button type="submit">Submit</button>
</form>
</div>
</td>
</tr>
Jquery
$(".customer-row").click(function () {
$(this).find("td.carrier-tiers").addClass('open-carrier-tiers');
});
$(".carrier-tiers-close-btn").click(function () {
$(this).parent().parent().removeClass('open-carrier-tiers');
});
CodePudding user response:
I think it's because the close event is being fired whenever the row is clicked because the event bubbles up. To fix this add an event.stopPropation() to the event handler. This will prevent the row click from also firing close. Try the code snippet below to see if it works for you.
$(".customer-row").click(function(e) {
$(this).find("td.carrier-tiers").addClass('open-carrier-tiers')
e.stopPropagation();
console.log(document.querySelector("td.carrier-tiers").className);
});
$(".carrier-tiers-close-btn").click(function(e) {
$(this).parent().parent().removeClass('open-carrier-tiers');
e.stopPropagation();
console.log(document.querySelector(".carrier-tiers-close-btn").className);
});
td {
padding: 0.5em;
border: 1px solid lightgray;
}
<table>
<tbody>
<tr >
<td>customer-row</td>
<td >
<div >
<li >close</li>
<form action="" method="POST">
<input type="text" name="Customer Name">
<button type="submit">Submit</button>
</form>
</div>
</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CodePudding user response:
Consider using more precise selectors.
$(function() {
$(".customer-row td:eq(0)").click(function() {
$(this).next("td.carrier-tiers").addClass('open-carrier-tiers');
});
$(".carrier-tiers-close-btn").click(function() {
$(this).closest('.open-carrier-tiers').removeClass('open-carrier-tiers');
});
});
.open-carrier-tiers {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr >
<td>customer-row</td>
<td >
<div >
<ul>
<li >close</li>
</ul>
<form action="" method="POST">
<input type="text" name="Customer Name">
<button type="submit">Submit</button>
</form>
</div>
</td>
</tr>
</tbody>
</table>
As you targeted the Row, the click event on the child could not bubble up.