Search code examples
javascriptjquery

Hiding single button with same class name


How can I hide a single button like when button with class name sbn is clicked. Also hide the button with class name cnl in same tr or td, and leave other buttons with same class name cnl visible.

So, I want, when I click send, that the cancel button is hidden, but not all cancel buttons only the one in the same tr or td.

<!DOCTYPE html>
<html>
<head>
  
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<tr>
<td>
  <button class="sbn">Send</button>
  <button class="cnl">Cancel</button>
  </td>
</tr>

<br />
<tr>
<td>
  <button class="sbn">Send</button>
  <button class="cnl">Cancel</button>
  </td>
</tr>

<br />
<tr>
<td>
  <button class="sbn">Send</button>
  <button class="cnl">Cancel</button>
  </td>
</tr>

<script type="text/javascript">
        $(document).ready(function() {
        $(".sbn").on('click', function() {
        $(this).html('clicked me!');
        $(this).attr('disabled', true);
        $(".cnl").hide();
    });
});
    </script>
</body>
</html>

Solution

  • Find the parent <td> with closest() and then find the cancel button inside it. parent() or parents() isn't perfect because a cell's html could change plus parents() could return multiple if you wrap the table inside another. So closest() would keep ability to change markup inside and outside the cell.

    Don't forget to add <table> so this would work with a proper markup.

    $(this).closest('td').find('.cnl').hide();
    

    $(".sbn").on('click', function() {
        $(this).html('clicked me!');
        $(this).attr('disabled', true);
        $(this).closest('td').find('.cnl').hide();
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <table>
    <tr>
    <td>
      <button class="sbn">Send</button>
      <button class="cnl">Cancel</button>
      </td>
    </tr>
    
    <br />
    <tr>
    <td>
      <button class="sbn">Send</button>
      <button class="cnl">Cancel</button>
      </td>
    </tr>
    
    <br />
    <tr>
    <td>
      <button class="sbn">Send</button>
      <button class="cnl">Cancel</button>
      </td>
    </tr>
    </table>