javascript - Jquery Alert response after route looped via foreach
Im looking to display an alert message with Jquery after clicking route button. The button is generated with foreach loop in the view.
The problem that it will only show the alert with clicking the first looped button, the subsequent won't show any alert.
Been searching around and haven't found any solution yet.
View
@foreach ($items as $item)
<a href="{{ route ('cart.add', $item->id)}}" id="cartAlert">Shop</a>
@endforeach
and Jquery code is
$("#cartAlert").on("click", function(){
alert("SomeText");
});
Thanks all!
Answer
Solution:
like @danronmoon said your tag need unique id. Change id for each element or add a class for every <a>
tag
<a href="{{ route ('cart.add', $item->id)}}" class="cartAlert">Shop</a>
In js
$("body").on("click",".cartAlert", function(){
//get this link attribute using $(this).attr("your_custom_attribute");
alert("SomeText");
});
Answer
Solution:
Id should be unique but in the loop, you create same name id:
//Replace id attribute with class from anchor tag like below:
<a href="{{ route ('cart.add', $item->id)}}" class="cart">Shop</a>
In js:
$("body").on("click",".cart", function(){
alert("Your text");
});
Source