May 16, 2013

JQuery single click event on a group of buttons

Ahmd0’s Question:

I’m using the following JQuery code to trap clicks on a single button:

$(function () {

    //Set up click event on the Remove button
    $('#ButtonRemove').click(function (event) {
    //Process button click event
    }
}

where the HTML itself is this:

<input type="submit" name="ButtonRemove" value="Remove Now" id="ButtonRemove" />

But one of my pages is generated dynamically, which means that it can have a variable number of Remove Now buttons, each having the following HTML:

<input type="submit" name="ButtonRemove_01" value="Remove Now" id="ButtonRemove_01" />
<input type="submit" name="ButtonRemove_02" value="Remove Now" id="ButtonRemove_02" />
...
and so on

So can I adjust my JQuery statement to catch all those buttons in one method?

EDIT: Wow. Thank you everyone! There’re so many ways to do it. JQuery is very handy!

There are several ways. If you want to catch event for all submit buttons.

$(":submit").on("click", function() {
 // Carry on
});

But it seems like you are trying to select element that start with ButtonRemove. So

$("[name^='ButtonRemove']").on("click", function() {
    // This function will apply on the elements whose name start with "ButtonRemove"
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!