problem with utilizing the image id when using a jQuery find selector

https://i.sstatic.net/1jm03.pngI am facing an issue where I need to dynamically pass a value in the find() selector to change the image. Here is the code I am using:

 $('.vd-accordion-grid .collapse').on('shown.bs.collapse', function() {
            var imageid=$(this).parent().find("img").attr("id");
            var crid='img#'+imageid;
        alert("image id :::   "+imageid);
        alert("crid::   "+crid);
           $(this).parent().find(crid).attr("src", "resources/vidal/images/accordion_down.svg");
        }).on('hidden.bs.collapse', function() {
           $(this).parent().find(crid).attr("src", "resources/vidal/images/accordion_right.svg");
       });

However, the image is not changing as expected. Interestingly, when I hard code the image id in the find method, the image changes successfully.

 $(this).parent().find('img#picid0').attr("src", "resources/vidal/images/accordion_down.svg");

I have actually written HTML code within Java custom tags. Here is an example of the code snippet:

"<a data-toggle=\"collapse\" href=\"#collapse"+iClauseCnt+"\" aria-expanded=\"true\" aria-controls=\"collapse"+iClauseCnt+"\" class=\"\" style=\"color:white;font-size: 15px;\">");
                         "<img id=\"picid"+iClauseCnt+"\" src=\""+webcontext+"/resources/vidal/images/accordion_down.svg\" alt=\"accordion_down\">");
                         ""+eleClause.valueOf("@name"));
                         "</a>");

Answer №1

Your code looks good, but there is a small issue you should be aware of. In the on('hidden.bs.collapse') callback function, the variable crid is undefined because it was not declared within the scope of that function.

Take a look at the code below:

$('.vd-accordion-grid .collapse').on('shown.bs.collapse', function() {
        var imageid=$(this).parent().find("img").attr("id");
        var crid='img#'+imageid;
    alert("image id :::   "+imageid);
    alert("crid::   "+crid);
       $(this).parent().find(crid).attr("src", "resources/vidal/images/accordion_down.svg");
    }).on('hidden.bs.collapse', function() {
       // The issue with 'crid' being undefined was here <======================
       var imageid=$(this).parent().find("img").attr("id");
       var crid='img#'+imageid;
       $(this).parent().find(crid).attr("src", "resources/vidal/images/accordion_right.svg");
   });

Please let me know if this resolves the problem for you.

Answer №2

Consider attempting the following solution:

Your code seems to be correct, however it appears that you may not be referencing the image-id correctly. Please verify this.

Try adding the following line of code:

$(this).parent().find('img#'+imageid).attr("src", "resources/vidal/images/accordion_down.svg");

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

Acquire the <li> element when it is clicked using vanilla JavaScript

Whenever a user enters a value in an input field, my function automatically adds a <li> element to a <ul>. Additionally, the function assigns the attribute ( onclick="doneToggle" ) to the created <li>. function createListElement() { ...

Issue encountered during compilation of cordova application

While using cordova CLI version 6.2.3 to build my app, I encountered an error in the console during the build process: ANDROID_HOME=/usr/lib/android-sdk JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64 /usr/lib/jvm/java-8-openjdk-amd64/bin/java: symbol lookup ...

What is the trick to vertically aligning two inline block divs with different font sizes?

Within a single div element, there are two child divs styled as inline-block with different font sizes. This results in varying heights for each child div. What criteria does the browser use to vertically position the left child div? Why don't they b ...

Can an unordered list be nested inside an inline list item in HTML or XHTML?

Take note that the li with child ul is set to display:inline - example code provided below <style type="text/css"> ul.nav_main li { display: inline } ul.nav_submenu li { display: block } </style> <ul class="nav_main"> <li>I ...

Tips for sending information using ajax to a python code?

I have an HTML page that sends values to a Python script. I am looking to receive the data sent and ensure that the script runs consistently to receive multiple sets of data. How can I achieve this? Here is my jQuery: $(function(){ $("#submit ...

Applying Dual Textures to a Cube in Three.js

Currently, I am working on a project where I am trying to apply both texture and an image to a box geometry cube. The material I am using is MeshBasicMaterial. I have used CanvasTexture for one texture and TextureLoader for the image. However, I am encount ...

Handling Jquery Validation with an Ajax Call on Submit

My form contains multiple select dropdowns with the name attribute set to "select[]". I am using Jquery Validation to validate the form, and upon successful validation, the Submit handler triggers an Ajax call to send all form keys and values as an array. ...

Unable to dial phone numbers when clicking 'Click to call' link on Android devices

Within my Cordova android application, I have a link set up like this: <a href = "tel:011123456789">Click to Call</a> While this click-to-call functionality works smoothly in IOS, it seems to be hindered in Android by an issue such as: 11- ...

What is the best way to bring a JavaScript library into a TypeScript project if the library includes a declaration file?

I have been attempting to utilize the type definitions from the callbag library. Unlike other libraries, callbag declares its type definition file within its package.json and is not included in DefinitelyTyped. However, when I try to import the library, I ...

Troubleshooting: Custom scroller feature in jQuery autocomplete is not functioning as

Having trouble with the jQuery mCustomScrollbar function for auto complete list. It works fine for simple content, but not in this specific case. Any assistance would be greatly appreciated. Thank you. ...

The Bootstrap popover is experiencing difficulty triggering events and displaying incomplete content

Is there a way to display popover content when a user clicks on a link? Currently, I am facing issues where the content is not showing and the trigger is not working properly. <div> <a class="user-info" href="#"><img src="a.png">us ...

The issue with updating an increment value in Mongoose has not been

I've encountered an issue while trying to increment a value and reassign it back to the key. const TopicSchema = mongoose.Schema({ count: Number }); topic.count += 2 The result I expected was 4, but instead, the value 22 is returned. Upon repea ...

Ways to expand the `Array.prototype` from an external library in a Node.js environment

While enjoying my time on hackerrank with pure JavaScript, I decided to steer clear of extra arrays or math libraries, unlike the convenience of using python. My approach is robust, but now I'm considering utilizing sugar.js or underscore. I came acr ...

Transferring data between two "Data" elements using Jquery Datatable

Utilizing the JQuery datatable, I have made the first column of my table clickable, which is labeled as RequestNo. Here's the code snippet: "ajax": { "url": "/Request/Search/LoadData", "type": "POST", "datatype": "j ...

utilizing eval() in order to retrieve a pointer to an include

I am currently developing a form widget where the form schema is fetched from an API and generated dynamically. The library I am using for this purpose (vue-form-generator) comes with built-in validators that are directly referenced within the library itse ...

Real-time array filtering with ReactJS for nested arrays

I am currently working on implementing a real-time filtering search feature for a lengthy list of items. The items are structured in the form of an array containing arrays with a string and an object, as shown below: const items = [ ["cats", [ ...

Using if/else statements in jQuery allows us to control the

Having some trouble with a basic code snippet. I am trying to find out if the #setactionsuccess section exists, and if it doesn't, I want to create it and add it at the beginning of the container. The first part is working fine, but the 'else&apo ...

What is the process for changing the name of a key in a MongoDB response

I am reviewing the following code snippet: // retrieve a specific question app.get('/:id', (req, res) => { Question.findById(req.params.id, function(err, response){ if (err) { return res.status(404).send(); } ...

Having trouble adjusting the image to fit properly in the carousel

I'm struggling to make the image fit properly within the carousel. Below is the CSS code I've been working with: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol cl ...

The JSON node fails to return a value after inserting data through an ajax request

I'm encountering an issue with a jQuery plugin that loads JSON data through an AJAX call and inserts it into an existing object. When I attempt to reference the newly inserted nodes, they show up as 'undefined', despite the data appearing co ...