16

I tried to find all ids starting with the string "matchItem_" and define a click-event for each. onclick i want wo execute a script with a URL parameter and change the image in this id-element. Unfortunately my syntax isn't right, I also tried with .each.function but I didn't get it.

$('[id^="matchItem_"]').each {
    
    $(this).click(){
     //...execute my script.php?urlparam=xx....;
     $(this).find('img').attr('src','/admin/images/ok.png');
    }

}
Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
michbeck
  • 745
  • 3
  • 9
  • 17
  • Possible duplicate: http://stackoverflow.com/questions/190253/jquery-selector-regular-expressions – PhD Aug 08 '11 at 16:21

2 Answers2

30

You don't need the each:

$('[id^="matchItem_"]').click(function() {
   // do something
   $(this).find('img').attr('src','/admin/images/ok.png');
});
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Mrchief
  • 75,126
  • 20
  • 142
  • 189
17

Your syntax is invalid because you forgot the functions.

$('[id^="matchItem_"]').each(function() {
    $(this).click(function(){
           //...execute my script.php?urlparam=xx....;
         $(this).find('img').attr('src','/admin/images/ok.png');
    });
});

Or if all you're doing is assigning the .click() handler, you can do it without the .each().

$('[id^="matchItem_"]').click(function(){
       //...execute my script.php?urlparam=xx....;
     $(this).find('img').attr('src','/admin/images/ok.png');    
});

This is because most jQuery methods will automatically act on every element in the jQuery object.

(edited to add closing parenthesis in code)

luke_mclachlan
  • 1,035
  • 1
  • 15
  • 35
user113716
  • 318,772
  • 63
  • 451
  • 440
  • @michbeck: You're welcome. By the way, it if all the elements are of the same tag type, like `
    `, you'll get better performance if you include the tag in your selector. `$('div[id^="matchItem_"]')`
    – user113716 Aug 08 '11 at 16:41