Reputation: 4077
I'm having trouble with this little thing. I have a code that looks like this:
<table>.........
<td>
<span class="editable" id="name"><?= $name ?></span>
<img class="edit_field" src="icons/edit.png"/>
</td>
.......
</table>
I want to obtain the id of the span, so that I can then change it (for example add an input box in it).
I have this:
$('.edit_field').live('click', function() {
var td = $(this).parent();
var span = td.find(".editable");
alert(span.id)
});
But it's not working... Any ideas? (I'm trying to do it like this so it's reusable)
Upvotes: 3
Views: 71
Reputation: 87073
Don't use live()
, because it has been deprecated. Use .on()
with jQuery 1.7+ for delegate event handling.
$('table tbody').on('click', '.edit_field', function() {
var img = $(this) ;
var td = img.parent(); // parent td ( if needed )
var span = img.prev('span'); // previous span ( a jQuery object )
alert( span.attr('id') ); // or span[0].id,here span[0] will gives an element
});
If your .edit_field
is not dynamically generated the use:
$('.edit_field').on('click', function() {
var img = $(this) ;
var td = img.parent(); // parent td ( if needed
var span = img.prev('span'); // previous span ( a jQuery object )
alert( span.attr('id') ); // or span[0].id,here span[0] will gives an element
});
Don't use same id
for multiple element. I assume that, you span
on each row have id=name
. If that's true, then use class
instead of id
.
Upvotes: 2
Reputation: 1825
try this http://jsfiddle.net/VPvSD/
$('table').on('click', '.edit_field', function() {
var td = $(this).parent();
var span = $(this).prev('span');
alert(span.attr("id"));
});
Upvotes: 2
Reputation: 6860
Try this one:
$('.edit_field').bind('click', function() {
var td_id = $(this).parents('td').attr('id');
alert(td_id);
});
It would be better if you use ID rather than class :
$('#name').bind('click', function() {
var td_id = $(this).parents('td').attr('id');
alert(td_id);
});
If you need to add some html content on it, then:
$('.edit_field').bind('click', function() {
var added_html = "<input type='text' />";
var td_id = $(this).parents('td').attr('id');
$('#'+td_id).html(added_html);
alert(td_id);
});
For this case, instead live, its better to use bind or on.
Upvotes: 1