简体   繁体   中英

Javascript - Select option is adding to the next row in the table

I am making a dynamic table, where the inputs are coming from a mongo database. The fifth and final column contains a select option dropdown, where if the user clicks an option from the dropdown, the text value of that option will show in column 3. However, I designed my code to make sure that if that text value already exists in column 3 then don't add it again. However, for some strange reason, when the text value already exists in column 3, it decides to add it to the next row in column 3 instead. I am unsure as to why this is happening but I think it may be due to the fact that I am using a forEach loop with addEventListeners instead it. I have provided 2 images, one is before I add "Human Resources" again to row 1" and the second image is what happens after I click on Human Resources from the dropdown in row 1 again. Honestly, the code could be better, but I am new to JavaScript.

Any help would be greatly appreciated. Thanks.

Images: 从第一行下拉列表中再次单击人力资源之前的图像

后图像 - 如图所示人力资源已添加到第二行

HTML:

    <table id="productivity-table">
        <thead>
            <tr>
                <th>Resource</th>
                <th>Productive Identity</th>
                <th>Impact Area</th>
                <th>Set Productive Identity</th>
                <th>Set Impact Area</th>
            </tr>
        </thead>

        <tbody>
            <tr></tr>
        </tbody>
    </table>

Js:

//List containing all departments
var alldepts = [];
var departmentID = document.createElement('select');
//getDepartments();

//Run Functions
getResources();
var old_selected_val = [];
var select_id = 1;

//Get Resources and corresponding information and display it in a table
function getResources(){
//getDept();
getDepartments();
fetch("________", {
}).then(response => {
    return response.json();
}).then(data => {

var table = document.getElementById("productivity-table");

for(var i=0; i < data.length; i++){
  var row = table.insertRow(table.rows.length - 1);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);

  cell1.classList.add("table-data");
  cell2.classList.add("table-data");
  cell3.classList.add("table-data");

  cell1.innerHTML = data[i].name;
  cell2.innerHTML = data[i].productive == 0 ? "No" : "Yes";

  //Cell3 - Create ul and li
  var impact_ul = document.createElement("ul");
  var impact_li = document.createElement("li");
  impact_li.innerHTML = data[i].entity;
  impact_li.setAttribute("style", "list-style-type:none");

  //Add delete button row
  var delete_span = document.createElement("span");
  delete_span.className = "delete";
  delete_span.innerHTML = "&times;"
  impact_li.appendChild(delete_span);

  impact_ul.appendChild(impact_li);
  cell3.appendChild(impact_ul);

  //Cell4 - Create select dropdown for impact area
  var cell4 = row.insertCell(3);
  cell4.classList.add("table-data");

  var impact_area = document.createElement('select');
  impact_area.setAttribute("id", "impact-area"); 

  let defaultOption = document.createElement('option');
  defaultOption.text = 'Is it Productive?';
  defaultOption.disabled = true;
  impact_area.add(defaultOption);
  impact_area.selectedIndex = 0;

  var productive_array = ["Yes", "No"];
  productive_array.forEach(item => {
    var impact_option = document.createElement("option");
    impact_option.text = item;
    impact_option.value = item;
    impact_area.appendChild(impact_option);
    cell4.appendChild(impact_area);
  })


  //Cell5 - Create department dropdown
  var dep_dropdown = document.createElement('select');
  dep_dropdown.classList.add("dep_select");
  select_id++;

  //dep_dropdown.length = 0;
  let dep_default = document.createElement('option');
  dep_default.text = 'Select Department';
  dep_default.disabled = true;
  dep_dropdown.add(dep_default);
  dep_dropdown.selectedIndex = 0;

  var cell5 = row.insertCell(4);
  alldepts.forEach(item => {
    cell5.classList.add("table-data");
    var dep_option = document.createElement("option");
    dep_option.text = item;
    dep_option.value = item;
    dep_dropdown.appendChild(dep_option);
    cell5.appendChild(dep_dropdown);

  })

    Department_Select("productivity-table", cell3, impact_ul, select_id);
    deleteButton();
}        
})
}


//Listen to department select option and update table accordingly 
function Department_Select(table_id, cell, ul, classLength) {
var table = document.getElementById(table_id);
var numRows = table.rows.length;
var i, s = null, tr, td;

  dep_select = document.querySelectorAll(".dep_select");

  dep_select.forEach(select => {
  //Get the inital select option value, to ensure the user is selecting a new value
  select.addEventListener("mouseenter", function(e){
    //Get table row number
    var rowNumber = this.parentNode.parentNode.rowIndex;

    //Store inital select option value to compare to a value that the user clicks on 
    old_selected_val[rowNumber-1] = select.value;
  });

  select.addEventListener("click", function(e){
    //Get Table row number
    var rowNumber = this.parentNode.parentNode.rowIndex;
    //Get current option value, that the user clicked on
    selected_val = select.value;

    //Checks if department already exists or not
    var Depexists = false;

    //If it's a new value, and if it doesn't already exist, add it to column 3
    if(selected_val != old_selected_val[rowNumber-1] && selected_val != "Select Department"){

      //Check if selected department already exists in list
      li_list = ul.getElementsByTagName('li');

      for (var i = 0; i < li_list.length; i++){
        //Each department has an &times x attached to it, it needs to be removed to get department name
        li_item = li_list[i].innerText;
        listed_dep = li_item.substring(0, li_item.length-1);

        //Check selected department exists
        if(selected_val == listed_dep){
          Depexists = true;
        }
      }

      //If department doesn't already exist on table, add the new department to column 3
      if(Depexists == false){
        
        //Create ul and li
        var impact_li = document.createElement("li");
        impact_li.innerHTML = selected_val;
        impact_li.setAttribute("style", "list-style-type:none");

        //Add delete button row
        var delete_span = document.createElement("span");
        delete_span.className = "delete";
        delete_span.innerHTML = "&times;"
        impact_li.appendChild(delete_span);

        ul.appendChild(impact_li);
        cell.appendChild(ul);

        //Button Listen for potential delete
        deleteButton();


        //Set the selected department value to be the old department value selected, for new incoming selections. 
        old_selected_val[rowNumber-1] = selected_val;
      }
    }
  });
});
}

It seems that you doesn't update ul 's reference in select.addEventListener("click" function and it refers to its last reference it has been assigned, which is was the next row (in fact in the last row which has value in 3rd column).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM