Sampath
Sampath

Reputation: 65870

Detect dynamic buttons using jquery

I have below kind of buttons on my view.Those are generated dynamically through server side code.So my question is I need to write generic jquery click event for do the relevant task of that buttons. (here I have generic method for all buttons on as server code).So how can I detect particular button for write my generic server call ?

Note : Common part of the all buttons is pre-paid-package

 <button id="pre-paid-package-12-day-camp" class="actionButton pre-paid-package-12-day-camp " name="key" value="pre-paid-package-12-day-camp" type="submit">
      Apply 12-Day Camp package
   </button>
<button id="pre-paid-package-20-day-camp" class="actionButton pre-paid-package-20-day-camp " name="key" value="pre-paid-package-20-day-camp" type="submit">
      Apply 20-Day Camp package
   </button>

Upvotes: 0

Views: 140

Answers (2)

Satpal
Satpal

Reputation: 133403

You can use .on() and jquery attribute selctor

$("button[id^='pre-paid-package']").on('click', function(){
   // code here
});

Here ^ is for starts with

Upvotes: 1

Johan
Johan

Reputation: 8266

You can do the following

The Html

    <button id="pre-paid-package-12-day-camp" class="actionButton pre-paid-package-12-day-camp " name="key" value="pre-paid-package-12-day-camp" type="submit">Apply 12-Day Camp package</button>
    <button id="pre-paid-package-20-day-camp" class="actionButton pre-paid-package-20-day-camp " name="key" value="pre-paid-package-20-day-camp" type="submit">Apply 20-Day Camp package</button>

Th JS

$(document).on('click', '[id^="pre-paid-package"]', function() {
    alert('clicked');
});

JsFiddle

Edit I have updated my answer, as per Anton's suggestion

Upvotes: 3

Related Questions