Reference to children of jQuery DOM object

To improve the quality of my code, I am attempting to write event handler functions that are able to identify their source. It's unclear whether my approach is incorrect or if the nesting of divs within tables on the page is causing issues.

The objective of the table/js below is to extract data from the attributes of the image tag and populate it into the input elements within the parent or 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 .form_item_wrapper table has a dynamic section where a list of .event_handler images can be populated. Once the $.get() function retrieves the entries and populates the data, it links the handlers to the images to trigger the onclick event for populate_shipment_details(event). This part functions correctly, with events triggering as expected and custom attributes from the image elements being readable. The following is the function 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 issue I am facing is that although form_wrapper correctly identifies the table containing the clicked image, Firebug indicates that foo_input appears "empty". For some reason, I am unable to create variables that target children within the form_wrapper. Ideally, I would like to write this code... which unfortunately does not work.

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

Answer №1

Here is the solution:

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

See it in action: http://jsfiddle.net/simevidas/HMJcy/

Note: The ID attribute had to be replaced with the class attribute on the INPUT elements, as IDs must be unique on a page where multiple INPUTs exist.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most efficient way to load a PHP page once the webpage has completely finished loading?

I'm relatively inexperienced when it comes to PHP and JQuery, so please bear with me if my knowledge is limited. Currently, I'm facing an issue where loading a small HTML table that contains information queried from game servers (like shown in t ...

Display the input text value when the button is clicked

I am a beginner in JavaScript and have created this HTML page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> Upon entering text into the input field and clicking on the submi ...

Steps to trigger an AngularJS modal window when the URL contains a query string

I am in the process of creating a website and I would like to have a $uiModal open when there is a querystring in the URL. If there is no query string, then the modal should not open. Here is the code snippet: myApp.controller('jobObjectiveController ...

Struggling with the development of a crossfading image gallery using jQuery's .animate() function while ensuring compatibility with IE8

Seeking assistance in creating a crossfading image gallery using jQuery and the .animate() function. I'm struggling to solve the issue of smooth fadeIn for the next image while maintaining compatibility with IE8. https://jsfiddle.net/Vimpil/fqhc1e9m/ ...

What is the best way to add Vue dependency using CDN?

For my project which is built using Kendo, Vue, .Net, Angular and jQuery, I need to incorporate https://www.npmjs.com/package/vue2-daterange-picker. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...

Incorporating an external HTML page's <title> tag into a different HTML page using jQuery

I am faced with a challenge involving two files: index.html and index2.html. Both of these files reside in the same directory on a local machine, without access to PHP or other server-side languages. My goal is to extract the <title>Page Title</ ...

Having trouble parsing JSON data from $_POST while utilizing AngularJS

While working in Angular, I encountered the following scenario: var data = {}; data['name'] = "test"; data['class'] = "testClass"; $http.post('http://testURL',data,function(data){ console.log(data); }); Upon inspecting the ...

Error in IE8: Object does not support this function in jQuery

In a recent project of mine, I successfully implemented sticky notes functionality. However, I encountered an issue with browser compatibility specifically related to IE8. Even though the code works perfectly in other browsers, it fails to run in IE8. The ...

Looking to streamline a JavaScript function, while also incorporating jQuery techniques

I've got this lengthy function for uploading photos using hidden iFrames, and while it does the job well, it's quite messy. I'm looking to simplify it into a cleaner function with fewer lines of code for easier maintenance. function simplif ...

Is it possible to create a compound editor within a cell in SlickGrid that contains two date fields

Currently, I am implementing SlickGrid with jQuery and I am interested in incorporating a compound editor within a cell similar to example 3a mentioned here. However, instead of two text fields, I would like to have two date fields. Although Example 3 dem ...

Combining disparate arrays with serialized name/value pairs

Is there a way to merge an unassociated array with serialized name/value pairs without manually iterating over them? //First, I select certain values from mytable var data = $('#mytable input:checked'); console.log(data); //Object[input attribu ...

What is the most effective method for creating a gallery of images on a website?

I am looking to create a website that primarily features images. This site is intended to visually showcase our products, allowing visitors to explore each part of our offerings on their own. Can anyone recommend a specific jQuery program I can use to ach ...

What are the steps to decode a JSON response using jQuery?

Working on a fun little web app for my significant other and me to keep track of movies we want to watch together. I'm exploring using TheMovieDatabase.org's API (which only supports JSON) to simplify the process of adding movies to our list. The ...

Having trouble retrieving AJAX response data using jQuery

I have been searching and attempting for hours without success. On my current page, I am displaying basic data from a database using PHP in an HTML table. However, I now want to incorporate AJAX functionality to refresh the data without reloading the page ...

Can JavaScript be used to dynamically update drop down lists in a gridview?

My gridview has multiple fields including PreviousPoints, GainedPoints, and TotalPoints. In edit mode, PreviousPoints is not editable, GainedPoints is a dropdown list, and TotalPoints is also a dropdown list. Whenever the selected value in GainedPoints ch ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Why does PHP external API access fail when requested from a different page on the same domain?

Currently, I am experimenting with cross-site scripting using Jquery and PHP/Symfony (HttpFoundation Component), but I'm facing difficulties in obtaining the necessary data from the server. My objective is to have Jquery fetch JSON from the local dom ...

Deselect the DOM element

Here is a jQuery code snippet: $(document).ready(function () { $(".story-area > h1, .story-area > p, .story-area > div > p").text(function () { return convertString($(this).text()); }); }); Additionally, there is a function de ...

Tips for enhancing the color saturations of cells that overlap in an HTML table

My goal is to enhance the color of overlapping cells in my HTML tables. For instance, when I click on cell 2, the .nextAll(':lt(5)') method will change the class of the next 4 cells. https://i.stack.imgur.com/mwv8x.png Next, clicking on cell 3 ...

Is your Phonegap and Jquery app experiencing delays in script loading?

I recently developed a phonegap + JQM application and encountered an issue with the loading time of external JavaScript files. To elaborate, when the app starts, the initial file that appears is loader.html. In this file, I have included several JS files ...