Use multiple dropdown menus in table as select lis

2019-08-26 05:53发布

问题:

so i have a users table, and i wanna add a column to the table where i can get to change the status of the user to active/inactive using bootstrap dropdown menu. here is the code for the tables:

<table class="table">
<thead>
  <tr>
    <th>#</th>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Status</th>
  </tr>
</thead>
<tbody>
  <tr>
    <th scope="row">1</th>
    <td>Mark</td>
    <td>Otto</td>
    <td>
      <div class="dropdown">
        <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Active
        </button>
        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
          <a class="dropdown-item" href="#">Active</a>
          <a class="dropdown-item" href="#">Inactive</a>
        </div>
      </div>
    </td>
  </tr>
  <tr>
    <th scope="row">2</th>
    <td>Jacob</td>
    <td>Thornton</td>
    <td>
      <div class="dropdown">
        <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Active
        </button>
        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
          <a class="dropdown-item" href="#">Active</a>
          <a class="dropdown-item" href="#">Inactive</a>
        </div>
      </div>
    </td>
  </tr>
  <tr>
    <th scope="row">3</th>
    <td>Larry</td>
    <td>the Bird</td>
    <td>
      <div class="dropdown">
        <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Active
        </button>
        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
          <a class="dropdown-item" href="#">Active</a>
          <a class="dropdown-item" href="#">Inactive</a>
        </div>
      </div>
    </td>
  </tr>
</tbody>

i added a JQuery snippet at the end. what this snippet does is changing the dropdown-menu label based on the clicked dropdown-item.

$(function(){
   $(".dropdown-menu").on('click', 'a', function(){
   $(".btn:first-child").text($(this).text());
   $(".btn:first-child").val($(this).text());
   });
});

when i change one record's status all other records are effected with that change. i tried using functions like .find() and .siblings() and even taking off the id="dropdownMenuButton" but couldn't fix it. could someone help me get around this issue.

回答1:

It looks like you don't understand how the jQuery snippet works. It should be:

$(function(){
   $(".dropdown-menu").on('click', 'a', function(){
       $(this).parents('.dropdown').find('button').text($(this).text());
   });
});

https://www.codeply.com/go/SkKl0OPReI