ro ko
ro ko

Reputation: 2986

Jquery selectors

Need a little help with my jquery here

I want all my button with a name starting with "my-" and finishing with "-press" to have a "click" event.

<input type="button" id="my-button-x-press" name="my-button-x-name-press" />

Buttons dynamically added to DOM should have the same event.

Upvotes: 5

Views: 164

Answers (5)

Andreas Wong
Andreas Wong

Reputation: 60506

http://api.jquery.com/category/selectors/

$('input[type=button][name^=my-][name$=-press]').click(function() {
   // code
})

To assign event to elements dynamically, use on http://api.jquery.com/on/ and supply your selector as the second argument to properly delegate event.

$('#container').on('click', 'input[type=button][name^=my-][name$=-press]', function() {
   // code
})

Assuming you are wrapping your inputs on #container, otherwise replace #container with body, but it's always preferable to select the closest ancestor of the selector

Upvotes: 10

imperium2335
imperium2335

Reputation: 24112

Off the top of my head:

$('input[name^="my-"]input[name$="-press"]').click(function(){
    //Stuff to happen.
});

If they are dynamically added to the dom:

$('input[name^="my-"]input[name$="-press"]').on('click', function(){
    //Stuff to happen.
});

Matpols answer is probably the simplest way to do it actually.

Upvotes: 0

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

you can do it like this

$('#my-'+dunamic_change_here+'-press').click(function(){
  // your code
});

Upvotes: 0

Guffa
Guffa

Reputation: 700162

You can use the attribute equals selector, the attribute starts with selector, and the attribute ends with selector, and the delegate method to catch events for elements that are added later on:

$('body').delegate('input[type=button][name^="my-"][name$="-press"]', 'click', function(){
  ...
});

Upvotes: 2

matpol
matpol

Reputation: 3074

give them all a class and do:

$('.classname').click(function(){etc.});

Upvotes: 0

Related Questions