0

I'm trying to rewrite some javascript code from an inline button onclick call to an regular javascript function.

I used the this reference in my code to remove a table column, which worked perfectly fine. Since I need to use the line of code on a few places I want it to be in a regular javascript function.

What I had:

<button type="button"  tabindex="-1" class="btn btn-secondary btn-tblrmv" onclick="if(!$(this).closest('tr').hasClass('notDeletable')){ $(this).closest('tr').remove(); }">
   <i class="mdi mdi-minus"></i>
</button>

as for the javasript function itself:

function removeTableRow(){
     if(!$(this).closest('tr').hasClass('notDeletable')){ 
          $(this).closest('tr').remove(); 
     }
}

Could someone please explain, why this isn't working as intended?

1
  • $(this) is referenced if you call it from inside an element, otherwise you need to pass it to your custom function as a parameter function removeTableRow(element){ Commented May 6, 2019 at 14:12

1 Answer 1

2

This do not work because this is not referring to the current element. Try with:

HTML:

  <button type="button" tabindex="-1" class="btn btn-secondary btn-tblrmv" onclick="removeTableRow(this)">
       <i class="mdi mdi-minus"></i>
    </button>

JS:

function removeTableRow (row) {
     if (!$(row).closest('tr').hasClass('notDeletable')) { 
          $(row).closest('tr').remove(); 
     }
}
Sign up to request clarification or add additional context in comments.

2 Comments

ah, wow. thank you very much. I didn't know I cloud just reference like this! Will mark you as correct in a couple days as soon as stackoverflow let's me
No problem mate, glad I've helped :)

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.