Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery click function inside a php loop

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?

like image 252
Joel James Avatar asked Jul 18 '14 10:07

Joel James


2 Answers

$(".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>
like image 161
user3702775 Avatar answered Sep 19 '22 21:09

user3702775


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();
});
like image 43
vortex Avatar answered Sep 19 '22 21:09

vortex