views:

20

answers:

1

Hi, I have a table that contains in each row an input and a "save" image.

<td>
 <div id="acp_1" style="margin-left:100px;display: inline">
   <input size="10" type="text" value="11:00" name="acpr_1" id="acpr_1" />
   <span class="modify-listener" id="ml_1">
     <img id="save_1" src="/images/skin/database_save.png" alt="modify"/>
   </span>
 </div>
</td>

<td>
 <div id="acp_2" style="margin-left:100px;display: inline">
   <input size="10" type="text" value="11:00" name="acpr_2" id="acpr_2" />
   <span class="modify-listener" id="ml_2">
     <img id="save_2" src="/images/skin/database_save.png" alt="modify"/>
   </span>
 </div>
</td>

The __number pattern is used to differentiate one row's element from another.

I need to capture the click event on the image, so I can save the input's value in the backend. Something like:

Event.observe('modify-listener', 'click', function(){
   ....

How can I detect which row's image was clicked so I can call an Ajax function with the right values?

Thanks.

+1  A: 

The technique you are searching for is called event delegation. It basically means that you handle an event on a higher lever of the tree so as to have only one event handler instead of many.

What you need to do is to find the container element that includes all the images (like the table that they are in), and use it as the base for event handling, and give its id to Event.observe. Then you can find out which img was clicked by using the Event.findElement method.

Event.observe('target', 'click', function(event) {
  alert( Event.findElement(event, 'IMG').id ); // e.g.: save_1
});

assuming that your table has an id #target

You can find a working demo here.

galambalazs