kores59
kores59

Reputation: 443

Removing <tr> from table with jQuery

I have 2 tables and every row has own button for deleting itself :

 <table class="table" id="Offers">
       <tr id="row1">
        <td><button type="button" id=1 class="removeOffer">X</button</td>
       </tr>   
 </table>

 <table class="table" id="OffersHistory">
       <tr class="History1">
        <td><button type="button" id=1 class="removeOfferHistory">X</button</td>
      </tr>   
 </table>

And two simple JQuery code, for every table , serving for remove :

   $(document).on('click', '.removeOffer', function(){
        var button_id = $(this).attr("id");
        $('#row'+button_id).remove();
   });

    $(document).on('click', '.removeOfferHistory', function(){
        var button_id = $(this).attr("id");
        $('.History'+button_id).remove();
    });

When i click on "X" button in the first table, it works fine. Row from first table is removed... But when i click on "X" button from second table, it removes row from second and first at the same time. Same row with same number from both tables are removed.. Why?

Upvotes: 1

Views: 65

Answers (3)

Parag Diwan
Parag Diwan

Reputation: 3918

Not sure you need to do this much coding.

You can simply do it by : -

$(document).ready(function() {
  $('button').click(function() {
     $(this).remove(); 
  });
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Remove button</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

    <button class="first" value="button1">button1</button>
    <button class="first" value="button1">button2</button>
    
</body>
</html>

Upvotes: -1

freefaller
freefaller

Reputation: 19953

Firstly, it's invalid HTML to have multiple elements with the same id.

But, you could simplify your code massively by using the power of jQuery...

$(function(){
  $("button").on("click", function(e) {
    e.preventDefault();
    $(this).closest("tr").remove();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>First Row</td>
    <td><button>X</button></td>
  </tr>   
  <tr>
    <td>Second Row</td>
    <td><button>X</button></td>
  </tr>   
</table>

Upvotes: 3

Rav
Rav

Reputation: 705

Both buttons have an ID of 1, change the ID or call the javascript function within the button

Upvotes: 0

Related Questions