1

I have a form in which a table of dynamic data is built with PHP. Within each row is an image that when clicked calls a jQuery function with a click event.

For example, if the image has an id of eventnfo_0, i have a function like this:

$("#eventnfo_0").click(function()

It all works fine as long as I have a defined click event for each row. The problem is, I need to make it dynamic because the number of rows can vary so it's not feasible to build a separate function as depicted above for each row.

My thought is there must be a way to call a jQuery function from an onclick event and pass a row number, but thus far, no dice.

I'm sure it's not an uncommon task, but I've not had any luck with my searches.

Any thoughts are appreciated.

bipen
  • 36,319
  • 9
  • 49
  • 62
Lane
  • 115
  • 2
  • 10

3 Answers3

3

there are many ways tyo do this... call a same class in each img and use it as a selector...

$('.yourClassName').click(function(){alert($(this).attr('id'));});

OR

 $("[id^='eventnfo_']").click(function(){
     alert($(this).attr('id'));
 });

since it is dynamically added this might help..

$(document).on('click',"[id^='eventnfo_']".click(function(){
     alert($(this).attr('id'));
 });

updated

you can use a data attributes for a rownumber and get it from jquery..

say this is your html.

 <img id="eventnfo_0" data-rownumber="1"/>

and jquery

$("[id^='eventnfo_']").click(function(){
     alert($(this).data('rownumber')); //this will alert 1
 });
bipen
  • 36,319
  • 9
  • 49
  • 62
  • Your second suggestion is working, but I need to pass a row number to the function so that I can get the appropriate event id from a hidden field. Thanks much for your help! – Lane Jan 22 '13 at 05:32
1
$("[id^='eventnfo_']").click(function(){
   alert(this.attr('id'));
});
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
0

If you are looking for dynamic rows you can not use .click, You should go with .on method which is the preferred way.

JS code

$("#table_id").on("click","tr [id^='eventnfo_']", function(){
 //your code goes here.
});

Above is called jQuery event delegation. Read more

Community
  • 1
  • 1
Techie
  • 44,706
  • 42
  • 157
  • 243