I link every row in my table with js
<tr class="clickable-row" data-row-id="{{$Offer->offer_nr}}" data-href='link'>
$(".clickable-row").click(function() {
window.location = $(this).data("href");
});
In my last cell, in every row, I have a button to open a modal. How can I cancel the window.location in JavaScript when I click the button to open my modal?
I made the last cell in my row unclickable with CSS:
pointer-events: none;
but the button is then also unclickable
I tried also to stop the window.location when I click on the button with
$(document).on('click', '.delete-record', function (e) {
e.preventDefault();
}
>Solution :
You can detect if the button was clicked using the target of what was clicked.
$(".clickable-row").click(function(e) {
const deleteClicked = e.target.closest('.delete-record');
if (deleteClicked) {
// call delete modal if you want
return false;
}
// window.location = $(this).data("href");
console.log($(this).data("href"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="clickable-row" data-href="a">
<td>a</td>
<td><button class="delete-record">X</button>
</tr>
<tr class="clickable-row" data-href="b">
<td>b</td>
<td><button class="delete-record">X</button>
</tr>
</tbody>
</table>
or you can stop the event from going down the tree, but you can not use event delegation on the document because the event has already been fired on the row by the time it gets to the document. So you would need to bind to the buttons directly.
$(".clickable-row").click(function(e) {
// window.location = $(this).data("href");
console.log("clicked row:", $(this).data("href"));
});
$(".delete-record").click(function(e) {
e.stopPropagation();
console.log("clicked button");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="clickable-row" data-href="a">
<td>a</td>
<td><button class="delete-record">X</button>
</tr>
<tr class="clickable-row" data-href="b">
<td>b</td>
<td><button class="delete-record">X</button>
</tr>
</tbody>
</table>