Home > Software design >  Duplicate users(entries) should not be add in table
Duplicate users(entries) should not be add in table

Time:12-09

I'm facing an issue. i have a dropdown contains list of users fetching from database. When i select a user from dropdown it appends on below table and when i select the same user again it again appends on below table as a new row. So i want to stop duplicating same user in table.

Here's my View Code

<div  style="display:none" id="user-container">
            <label>User</label>
            <select id="users"  disabled="disabled">
              <option value="">Select User</option>
            </select>
            <p ><span id="users_error"></span></p>
          </div>

Here's my JavaScript Code

PostMyData(obj, '/Admin/Meetings/GetUserGroupUsers', (res) => {
   
  if (res.Code === 0 || res.Code === -1) {
    alert(res.Message);
  }
  if (res.Code === 1) {
 
    $('#users').html('');
 
    $('#users').append('<option value="">Select User</option>');
 
    res.Data.map(item => {
      $('#users').append(`<option value="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
    });
 
    $('#users').prop('disabled', false);
  }

CodePudding user response:

I think dynamically giving an id will do this job.Lets say you are giving giving id based of id value, then you can easily find if same id exits or not.

PostMyData(obj, '/Admin/Meetings/GetUserGroupUsers', (res) => {
   users = document.getElementById("users");
    if (res.Code === 0 || res.Code === -1) {
      alert(res.Message);
    }
    if (res.Code === 1) {
   
      users.html('');
   
      users.append('<option value="">Select User</option>');
   
      res.Data.map(item => {
        if(!users.querySelector(item.UserId))
        users.append(`<option value="${item.UserId}" id="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
      });
   
      users.prop('disabled', false);
    }

CodePudding user response:

I don't know what do you mean by duplicating same user in table, If you mean you want prevent duplicating user in the dropDown list you can try on this code, if not, please provide more details about the table you are working on.

 ...
 const usersList=  $('#users');
 res.Data.forEach(item => {
  if(usersList.find(`option[value=${item.UserId}]`).length > 0){
    return ; // do nothing
  }
  usersList.append(`<option value="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
});
...
  • Related