Reputation: 3
I have following Code in my view.
@foreach($categories as $category)
<tr class="cat-row">
<td class="cat-id">{{$category->id}}</td>
<td>{{$category->name}}</td>
<td><a href="" class="btn btn-danger">Get ID</a></td>
</tr>
@endforeach
If I want to get a simple alert with the id of the current row by clicking the Get ID button, what should I do in jquery?
Upvotes: 0
Views: 2787
Reputation: 706
Here is solution for that
$(".getId").on('click',function() {
let id = $(this).attr('id');
console.log(id);
});
/*PHP File*/
@foreach($categories as $category)
<tr class="cat-row">
<td class="cat-id">{{$category->id}}</td>
<td>{{$category->name}}</td>
<td><a href="" class="btn btn-danger getId" data-id="{{$category->id}}">Get ID</a></td>
</tr>
@endforeach
Upvotes: 0
Reputation: 2232
Here is my contribution.
Something very similar to what Kapsonfire wrote.
$(document).on('click', '.btn-danger', (e) => {
let target = e.target;
let topmostParent = target.parentElement.parentElement;
let id = $(topmostParent).find('.cat-id').text();
console.log(id);
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<table>
<tr class="cat-row">
<td class="cat-id">123</td>
<td>Test</td>
<td><a href="#" class="btn btn-danger">Get ID</a></td>
</tr>
<tr class="cat-row">
<td class="cat-id">124</td>
<td>Test</td>
<td><a href="#" class="btn btn-danger">Get ID</a></td>
</tr>
<tr class="cat-row">
<td class="cat-id">125</td>
<td>Test</td>
<td><a href="#" class="btn btn-danger">Get ID</a></td>
</tr>
<tr class="cat-row">
<td class="cat-id">126</td>
<td>Test</td>
<td><a href="#" class="btn btn-danger">Get ID</a></td>
</tr>
</table>
Upvotes: 0
Reputation: 1033
give the get id button a proper selector like class '.getid'
$(document).on('click', '.getid', function() {
let id = $(this).closest('tr').find('.cat-id').text();
console.log(id);
});
you have to bind the listener to document to apply on dynamically inserted dom
Upvotes: 1