Jake
Jake

Reputation: 26117

JQuery - Add click event to multiple elements

I have the following:

$('#applicationsGrid tbody').on('click', 'td.details-control', function () {
    var formattedData = dosomething();
    $(this).parent('tr').after(formattedData);
});

$('#applicationsGrid tbody').on('click', 'td.child-details-control', function () {
    var formattedData = dosomething();
    $(this).parent('tr').after(formattedData);
});

$('#applicationsGrid tbody').on('click', 'td.grand-child-details-control', function () {
    var formattedData = dosomething();
    $(this).parent('tr').after(formattedData);
});

How can I combine all the "on" events into one click event that would take care of clicking on 'td.details-control', 'td.child-details-control', 'td.grand-child-details-control', so I can reduce duplicate code?

Upvotes: 0

Views: 74

Answers (2)

Balachandran
Balachandran

Reputation: 9637

Just you can concatenate with multiselector

$('#applicationsGrid tbody').on('click', 'td.details-control,td.child-details-control,td.grand-child-details-control', function () {
              var formattedData = dosomething();
              $(this).parent('tr').after(formattedData);
            });

OR use end with selector ,in your case all class value is ended with details-control,

  $('#applicationsGrid tbody').on('click', ,'td[class$=details-control]', function () {
              var formattedData = dosomething();
              $(this).parent('tr').after(formattedData);
            });

Upvotes: 1

Sudharsan S
Sudharsan S

Reputation: 15393

Use Multiple Selector (“selector1, selector2, selectorN”) in jquery

$('#applicationsGrid tbody').on('click', 'td.details-control,td.child-details-control,td.grand-child-details-control', function () {
      var formattedData = dosomething();
      $(this).parent('tr').after(formattedData);
});

Learn Multiple selector

Upvotes: 2

Related Questions