MaryBaker MaryBaker - 1 year ago 37
Javascript Question

Using JSON to retrieve different id from data base

I have an HTML img tag with an empty src and I use JSON and jquery to retrieve the src of the img from the database when the user hovers over a parent span that contain the img tag. The problem is when I retrieve the src with JSON everything is fine and the image src is retrieved but I a loop set for this span in the very same page, so when the first image is already retrieved it's src is applied for the other looped span images. It is like retrieving the same id of the first image for the other different looped images that suppose to have different id for different content image contents.

here's is my code :

var id=$('#im').attr('value');

Here is the HTML

{loop="data"} <span class="foo" id="key">{$value.user_key}</span> <span class="foo">
<img alt="ther is an image here" src="" value="{$}" id="im"/></span>


The problem is that you have duplicated IDs on your page. So, $('#key') will always return the first DIV with the id key, the same for $('#im'). Instead this $('img') will select all images on your page. Here is a demo to illustrate the problem:

console.log("$('#key') count:"+$('#key').length);
console.log("$('#img') count:"+$('#key').length);
console.log("$('img') count:"+$('img').length);

  console.log("ID hovered: "+$('#im').attr('value'));
<script src=""></script>
<div id="key"> Div 1
  <img src="" id="im" value="1"  />
<div id="key"> Div 2
  <img src="" id="im" value="2"  />
<div id="key"> Div 3
  <img src="" id="im" value="3"  />
<div id="key"> Div 4
  <img src="" id="im" value="4"  />

To solve that you need to use another selector, for example, use a class:

        //This will select all images inside 'this' (hovered .key)
        var img = $('img', this);
        $.post('getjson.php',{id : img.attr('value')},function(data){


  {loop="data"} <span class="foo" id="key">{$value.user_key}</span> 
      <span class="foo my-selector"> <!-- add class my-selector -->
         <img alt="ther is an image here" src="" value="{$}" id="im"/>