Reputation: 431
I have a list like below
<tr>
<td>val1</td>
<td>val2</td>
<td>val3</td>
<td><span class="span_view">1</span><a class="view_class">View</a></td>
</tr>
<tr>
<td>value1</td>
<td>value2</td>
<td>value3</td>
<td><span class="span_view">2</span><a class="view_class">View</a></td>
</tr>
If I click on view link then it should print the associated value of span e.g for the first view it will be 1 and for 2nd one it will be 2. I have written the following code but it is not printing the value:
$('.view_class').live('click',function(){
var parentDiv = $(this).closest('span');
alert(parentDiv);
var curprice=parentDiv.find('span[id=span_view]').val();
alert(curprice);
});
it is showing [object Object]
and undefined
.
Please guide me where is the problem.
Thanks in advance.
Upvotes: 1
Views: 1640
Reputation: 48972
Try:
$('.view_class').on('click',function(){
var parentDiv = $(this).parent();
var curprice = parentDiv.find('.span_view').html();
alert(curprice);
});
Using the parent as the context to create more maintainable code. In case you need to re-order the spans, your code still works.
Or use delegated event to attach only 1 event handler and works also in case you load the list dynamically using ajax.
$(document).on('click','.view_class',function(){
var parentDiv = $(this).parent();
var curprice = parentDiv.find('.span_view').html();
alert(curprice);
});
Upvotes: 0
Reputation: 16122
replace:
$('.view_class').live('click',function(){
var parentDiv = $(this).closest('span');
alert(parentDiv);
var curprice=parentDiv.find('span[id=span_view]').val();
alert(curprice);
});
on:
$('.view_class').on('click',function(){
var curprice=$(this).closest('span.span_view').html();
alert(curprice);
});
Upvotes: 2