Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 520
ro ko Avatar asked Apr 11 '12 06:04

ro ko


2 Answers

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

like image 121
Andreas Wong Avatar answered Oct 12 '22 12:10

Andreas Wong


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(){
  ...
});
like image 39
Guffa Avatar answered Oct 12 '22 11:10

Guffa