0

The below jquery snippet is working fine. I want to know how to write it as function which accepts the table1 as a parameter so that I can reuse this function in other section of the code. For e.g. If I have table with id table2 instead of adding new function I should re use the existing one

$(document).ready(function(){    
    $("#table1").on('click','.btnDelete',function(){
        $(this).closest('tr').remove();
  });
});
1
  • 1
    Write selector based on that. There is no need to register more functions for a similar events Commented Nov 23, 2016 at 10:18

5 Answers 5

3

There are many ways to handle use attribute selector in one way

  $("[id^=table]").on('click','.btnDelete',function(){
        $(this).closest('tr').remove();
  });
Sign up to request clarification or add additional context in comments.

Comments

1

Take a different approach and assign a behaviour class, eg:

$(".table-with-removable-rows").on('click','.btnDelete',function(){
    $(this).closest('tr').remove();
});

then whenever you want this behaviour, you add that class, eg:

<table class="table-with-removable-rows">...

that way there's:

  • no need to change any code
  • it doesn't affect every table, only the ones you set this to
  • you don't need to format the id to trigger the behaviour
  • the behaviour is clear on the html

1 Comment

I like this approach
0

It's pretty easy, just name your function and use it wherever you want

$(document).ready(function() {    
  var deleteAction = function() {
     $(this).closest('tr').remove();
  };
  $("#table1").on('click', '.btnDelete', deleteAction);
  $("#table2").on('click', '.btnDelete', deleteAction);
  $(".btnDelete").on('click', deleteAction);
  // etc etc.
});

Comments

0
   $(document).ready(function(){    
      $("#table1").on('click','.btnDelete',function(){
         RemoveRow($(this));
      });

      function RemoveRow(table){
         $(table).closest('tr').remove();
      }

  });

Comments

0

 $("#table1,#table2,#table3").on('click', '.btnDelete', function() {
   $(this).closest('tr').remove();
 });

$("[id^=table]").on('click', '.btnDelete', function() {
  $(this).closest('tr').remove();
});

Comments

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.