Home > Mobile >  How to limit the number of rows selected in a table for a user?
How to limit the number of rows selected in a table for a user?

Time:01-03

I am doing a project for a gym management where I am required to display a table of members from database and a trainer should be able to add a maximum of 5 members into his table but I am having an issue that the button would count for 5 and then when the button is disabled it will only disable for the first button.I think it is because they all have the same id and function but I don't know how to make it all linked so when 5 members are selected all buttons are disabled.

enter image description here

var counter = 1;

function a() {
  if (counter < 5) {
    document.getElementById('a').innerHTML  = "<input type='hidden'>";
    counter  ;
  } else {
    document.getElementById("id").disabled = true;
  }
}

document.querySelector(document).ready(function() {
  document.querySelector('.addbtn').click(function() {
    document.querySelector(this).html(document.querySelector(this).html() == 'add' ? 'modify' : 'add');
  });
});
<!DOCTYPE html>
<html>

<head>
  <script src="table1.js"></script>
</head>

<body>
  <h1>Select 5 Members to train</h1>

  <table border="1">
    <tr>
      <th>User_Id</th>
      <th>User_Name</th>
      <th>User_Email</th>
      <th>ADD</th>
    </tr>

    <tr>
      <td>1</td>
      <td>Memeber 1</td>
      <td>[email protected]</td>
      <td><button  id="id" onClick="a();">add
            </button></td>
    </tr>
    <div id='a'></div>
    </tr>


    <tr>
      <td>2</td>
      <td>Memeber 2</td>
      <td>[email protected]</td>
      <td><button  id="id" onClick="a();">add 
            </button></td>
    </tr>
    <div id='a'></div>
    </tr>


    <tr>
      <td>3</td>
      <td>Memeber 3</td>
      <td>[email protected]</td>
      <td><button  id="id" onClick="a();">add    
            </button></td>
    </tr>
    <div id='a'></div>
    </tr>


    <tr>
      <td>4</td>
      <td>Memeber 4</td>
      <td>[email protected]</td>
      <td><button  id="id" onClick="a();">add   
           </button></td>
    </tr>
    <div id='a'></div>
    </tr>


    <tr>
      <td>5</td>
      <td>Memeber 5</td>
      <td>[email protected]</td>
      <td><button  id="id" onClick="a();">add 
            </button></td>
    </tr>
    <div id='a'></div>
    </tr>

    <tr>
      <td>6</td>
      <td>Memeber 6</td>
      <td>[email protected]</td>
      <td><button  id="id" onClick="a();">add
            </button></td>
    </tr>
    <div id='a'></div>
    </tr>

  </table>

</body>

</html>

CodePudding user response:

First of all, yes the id is not meant to use it multiple times.

Instead of :

document.getElementById("id").disabled=true;

You can try this :

document.querySelectorAll('.addbtn').forEach((btn) => {
  btn.disabled = true;
})
  • Related