JQuery selectors

Need a little help with my jquery here

I need my entire button with a name starting with "my-" and ending 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 the DOM must have the same event.

+5
source share
5 answers

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

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

To dynamically assign events to elements, use on http://api.jquery.com/on/ and set your selector as the second argument to the correct delegateevent.

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

Assuming you insert your inputs on #container, otherwise replace #containerwith body, but it is always preferable to choose the closest ancestorselector

+10

, , , delegate , :

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

give them all classes and do:

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

you can do it like this

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

Above my head:

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

If they are dynamically added to dom:

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

Matpols answer is probably the easiest way to actually do this.

0
source

All Articles