0

Possible Duplicate:
Wildcards in jQuery selectors

Say I have several buttons on my page, with id tags as id_1, id_2, id_3 etc

I want a function to cover all of them being pressed, so something that checks if the first 3 characters are id_.

 $("?????").click(function(event) {

What replaces the ??????

I can't use classes instead, in this instance.

Community
  • 1
  • 1
user1022585
  • 13,061
  • 21
  • 55
  • 75

3 Answers3

4

This would also work:

$('[id^=id_]').click(function() {
  //Do stuff here
});

This selects all elements whose id attribute begins with id_, so id_1, id_2, id_3, etc... would all be selected.

However, it might be more appropriate to use the class attribute as a selector. Unlike the id attribute, the class attribute does not have to be unique. So, for example, you can have 5 buttons on your page, each with a class name of clickMe, and employ the following code which will listen for a click on any of the buttons:

$('.clickMe').click(function() {
  //Do stuff here
});

Hope that helps.

Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195
2

How about this (I'm pretty new to JavaScript, might not work):

for(var i = 0; i < maxId; i++) {
  $("#id_"+i).click(function(e) {
    //Blah blah blah
  });
}
Linuxios
  • 34,849
  • 13
  • 91
  • 116
1

Try this

$(function(){
    $('button[id^="id_"]').on('click', function(e){
        alert($(this).attr('id'));
    });
});​

Here's an example.

The Alpha
  • 143,660
  • 29
  • 287
  • 307