I have a foreach loop in php like below.
<?php
$i = 0;
foreach ($query as $value) { ?>
<button id="show[<?php echo $i;?>]" class="btn btn-success" type="button">View</button>
<div id="blah[<?php echo $i;?>]">Joel</div>
<?php
$i++
} ?>
Now this loop work fine and I am getting id for each buttons and divs with unique id. But I want to add a jquery click function like below.
$("#show").click(function(){
$("blah").hide();
});
But since it is inside a loop and have different id's with them how to add this jquery function for each buttons?
$(".btn").click(function(){
var id = $(this).attr('id');
var n = id.replace("show",'');
$("#blah"+n).hide();
});
Also replace your buttons with this code
<button id="show-<?php echo $i;?>" class="btn btn-success" type="button">Clear</button>
<div id="blah-<?php echo $i;?>">Joel</div>
for php:
<?php foreach ($query as $key => $value) {?>
<button class="btn btn-success blah-toggler" type="button" data-target="blah-<?php echo $key ?>">
<div id="blah-<?php echo $key ?>">Joel</div>
<?php }?>
then in jquery:
$(".blah-toggler").on("click", function(){
var t = $(this);
$('#' + t.data('target')).hide();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With