Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Finding an element

Tags:

jquery

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)

like image 366
luqita Avatar asked Jul 13 '26 03:07

luqita


2 Answers

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"));
});
like image 64
Vinit Avatar answered Jul 14 '26 15:07

Vinit


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
});

Note

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.

like image 45
thecodeparadox Avatar answered Jul 14 '26 17:07

thecodeparadox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!