Reputation: 2417
I have a comment's reply form which is loop through database, each of the form and reply button are dynamically assigned with difference ID, such as <button type="button" id="btn_reply_comment_'.$row['id'].'">Post Reply</button>
as well as a form ID with <form id="reply_form_'.$row['id'].'">
.
I want to make an ajax call trigger by the #btn_reply_comment_{follow by dynamic ID}
, but I cannot assign dynamic ID to match with which button is clicked, how can it be done?
Jquery to trigger ajax by button click:
$('body').on('click', '#btn_reply_comment_'+id, function(){
var parameters = $(this).closest('form').serialize();
alert(parameters);
//ajax call here
});
Upvotes: 0
Views: 7768
Reputation: 4925
html
<button id="btn_reply_comment_'.$row['id'].'" class="className">Post Reply</button>
jquery
$(".className").click(function(){
var parameters = $(this).closest('form').serialize();
alert(parameters);
//ajax call here
});
Upvotes: 1
Reputation: 11983
Stash the ID on the elements themselves. No need to use string manipulation.
HTML
"<button type="button" class="btn_reply_comment" data-rowid="'.$row['id'].'">"
"<form id="reply_form" data-rowid="'.$row['id'].'">"
Javascript
$('body').on('click', '.btn_reply_comment', function(){
var rowId = $(this).data('rowid'),
parameters = $('form[data-rowid=' +rowId + ']').serialize();
alert(parameters);
//ajax call here
});
Upvotes: 0
Reputation: 71384
You should use a class for this. And set up the click handler on teh class.
So your HTML might look like:
<button type="button" id="btn_reply_comment_'.$row['id'].'" class="post_reply_button">Post Reply</button>
And your jQuery would look like:
$('body').on('click', '.post_reply_button', function(){
var parameters = $(this).closest('form').serialize();
alert(parameters);
//ajax call here
});
Upvotes: 1