skip to Main Content

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 class="form-group col-md-4 " style="display:none" id="user-container">
            <label>User</label>
            <select id="users" class="form-control" disabled="disabled">
              <option value="">Select User</option>
            </select>
            <p class="validate-error"><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);
  }

2

Answers


  1. 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>`);
    });
    ...
    
    Login or Signup to reply.
  2. 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);
        }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search