Reputation:
i did a loop in which I put few buttons according to the number of colors i've got, but no matter what button i click, it shows like i click the first one, the buttons are unique, i set them id.
html - loop
<td> <div> Add 2nd color </div> </td>
<td style="min-width:121px;position:relative;">
'.$pop['pop3'].'
<div id= "'.$i.'" class="btn save_img"> Choose image </div>
js:
$('.save_img').click(function(){
onChooseImageClick();
});
function onChooseImageClick()
{
var rowId = $('.save_img').closest('tr').attr('row_id');
alert(rowId);
the alert gives me always number 1, no matter what button i click, any points to look for the problem? as i tried almost everything, andi have no clue where to continue looking.
Upvotes: 0
Views: 394
Reputation: 388316
You need to find the closest tr
of the clicked save_img
for that you need to know which was the clicked element. this
inside the click handler refers to the element targeted by the handle(the save_img
element here), so pass that to onChooseImageClick
then use that element reference to find the tr
element
$('.save_img').click(function () {
onChooseImageClick(this);
});
function onChooseImageClick(el) {
var rowId = $(el).closest('tr').attr('row_id');
alert(rowId);
}
$('.save_img').closest('tr')
will return all tr
elements that has a .save_img
element, then .attr('row_id')
will return the id
of the first element in that set.
As @John suggested below you can also use
$('.save_img').click(onChooseImageClick);
function onChooseImageClick(el) {
var rowId = $(this).closest('tr').attr('row_id');
alert(rowId);
}
Upvotes: 2