5

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.

5 Answers 5

10

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

Sign up to request clarification or add additional context in comments.

Comments

2

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(){
  ...
});

Comments

0

give them all a class and do:

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

Comments

0

you can do it like this

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

Comments

0

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.

1 Comment

If the inputs are dynamically inserted then the on() would have to be bound to an ancestor element, not the element that's dynamically inserted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.