0

View

<?php $no=1; foreach($result as $r){?>
  <span><?php echo $r['id'];?></span><span><?php echo $r['name'];?></span>
<button class="btn btn-success" id="<?php echo $no?>">Add</button>
<?php $no++;}?>

This php code will display 5 buttons with the different id (1,2,3 and so on). What I want to happen is when I click any of the 5 buttons the jQuery function will show its id. I have this code.

var btn = $('.btn-success').attr('id');
$('#'+btn).click(function(){
  alert(btn);
 }

but, it only appears for the first id.

avalon727
  • 15
  • 6

4 Answers4

2

$('.btn-success') gets all the elements, but when you add attr(), it only gets the attribute for the first element in the collection.

You can just attach the event handler to the entire collection, and use this.id to get the ID of the clicked element inside the event handler

$('.btn-success').on('click', function(){
    alert(this.id);
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Try following

$('.btn-success').click(function(){
    $(this).attr('id');
    alert(btn);
}

I would suggest not to use numbers as ID value, if possible. Check this link Valid ID and Name

Community
  • 1
  • 1
Lepanto
  • 1,413
  • 1
  • 8
  • 15
0

Try this..

$('.btn-success').on('click', function(){
    alert(this.id);
});
Jameem
  • 1,840
  • 3
  • 15
  • 26
0

You can do something like:

In you view:

<?php $no=1; foreach($result as $r){?>
   <span><?php echo $r['id'];?></span><span><?php echo $r['name'];?></span>
   <button onclick="abc(this.id)" class="btn btn-success" id="<?php echo $no?>">Add</button>
<?php $no++;}?>

Use this javascript function as :

function abc(id){
     alert(id);
}
Rushikesh
  • 176
  • 5