Reputation: 11
My code looks like this. If the value of textbox is empty it display an image abc.png If the value of a textbox is some value, it displays other image xyz.png
<td class= 'notesClass' id='selectoneN'>
<a href='#'>
<img class='notesImg' id='notesID' src='images/notes.png'/>
<input class='hiddenClass' value="+Col7+"></input>
</a>
</td>
I have used $('table tr td img').attr("src", "images/xyz.png");
but the problem is it replaces all img with xyz.png which is not what I want.
Upvotes: 1
Views: 157
Reputation: 218877
Note your selector:
$('table tr td img')
This will target any img
which is in any table. So if there's more than one, you're applying the logic to all of them. However, notice your markup:
<img class='notesImg' id='notesID' ...
Your element has an id
. id
s are required to be unique, so assuming you're not breaking that rule you can easily target that element:
$('#notesID')
If, on the other hand, you are breaking that rule, well, stop it. But more to the point that would mean you don't have a unique identifier for the element you're targeting. So, logically (not in terms of code but just in terms of the document structure), how would you identify that element?
For example, what is the JavaScript code which invokes this? Is it responding to an event handler? Is that event handler attached to the input
element? Is there a this
reference to that input
element? If so, you can identify its neighboring img
a couple of ways. This might work:
$(this).prev('img')
or perhaps something like this:
$(this).parent().find('img')
Essentially it's traversing the DOM from the known starting point (the input
) to find the nearby img
. You can move backward or forward in the DOM, or move up to a common parent and back down. It's a basic hierarchical structure that can be navigated by jQuery. Once you can logically identify how you would decide which element to choose, it's just a matter of using a jQuery selector (or combination of them) to express that logic.
Upvotes: 0
Reputation:
use id
to address
$('#notesID').attr(...)
and if image is cashed, send time as a parameter
var now = new Date();
$('#notesID').attr('src', 'path/to/image?'+now);
Upvotes: 0
Reputation: 30737
So use $('#notesID').attr("src", "images/xyz.png");
to target just that one img
by its id
#notesID
is essentially saying to jquery that you want to target an element by its ID (#
does this, where .
would target a css class) - along with the actual ID notesID
your selector - $('table tr td img')
- is is targeting ALL images in a table in a cell of a row of a table.
Upvotes: 0