DirtyBirdNJ
DirtyBirdNJ

Reputation: 592

jQuery DOM object referenced children

In an attempt to create cleaner code, I am trying to write event handler functions that are aware of where they get called from. I am not sure if what I'm trying to do is not the correct way to do things, or if the underlying nesting of divs within tables that the page is made up of is causing problems.

The goal of the below table/js is to take data from the attributes of the image tag, and populate them into the input elements within the parent/ancestor table.

Table Structure:

<table id="formbody">

    <tr><td>
    <table class="form_item_wrapper" id="form_item_1">

        <tr><td><div id="search_results"><img class="event_handler" foo="bar" /></div></td></tr>

    <tr><td>Foo: <input id="event_input" name="foo_input_1"></td></tr>
   </table>

    <table class="form_item_wrapper" id="form_item_1">
        <tr><td>
            <div id="search_results"><img class="event_handler" foo="baz" /></div>
        </td></tr>

     <tr><td>Foo: <input id="event_input" name="foo_input2"></td></tr>
    </table>

     </td></tr>


</table>

Each of the .form_item_wrapper tables has a section that can dynamically populate the list of .event_handler images. Once the $.get() that retrieves the entries populates the data, it attaches the handlers to the images to fire populate_shipment_details(event) onclick. That part works fine, the events fire correctly and I can read my custom attributes from the image elements. This is the function that gets called when one of the images is clicked:

function populate_shipment_details(event){

var form_wrapper = $(event.target).closest('.form_item_wrapper');

var foo_input = $(form_wrapper).children('#event_input');

    foo_input.val($(event.target).attr('foo'));

}

The problem I am having is that while form_wrapper properly resolves to the table containing the image that was clicked on, Firebug is showing that foo_input is showing up "emtpy" in Firebug. For whatever reason, I cannot create variables that point to children within the form_wrapper. Ideally, this is the code that I want to write... but doesn't work.

$(form_wrapper).children("#event_input").val($(event.target).attr('foo'));

Upvotes: 0

Views: 86

Answers (1)

Šime Vidas
Šime Vidas

Reputation: 185903

Here you go:

$('img.event_handler').click(function() {
    $(this).closest('tr').next().find('input.event_input').val($(this).attr('foo'));
});

Live demo: http://jsfiddle.net/simevidas/HMJcy/

Note: I had to replace the id attribute with the class attribute on the INPUT elements, since ID's have to be unique on the page, and you have multiple INPUT's.

Upvotes: 1

Related Questions