简体   繁体   中英

JS Array Splice to remove an element in an Array

I have a table being populated by an array containing a list of products and their quantities for an order to be placed by a customer. On the Order confirmation screen the user can remove items in the order by clicking the delete button associated with the particular row .

This is my HTML

<div id="summary">
    <table id="ordertable">
        <tr><th>Product</th>
        <th>Quantity</th>
        <th></th>
        </tr>
    </table>
</div>

This is my JS

if($.cookie('order_cookie') != undefined){
    productArray = JSON.parse($.cookie('order_cookie'));
    $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
}

var ordertable = document.getElementById("ordertable");

//Loop through the array
for(i = 0; i < productArray.length; i ++){
    item = productArray[i];
    var x = item.split(':');
    var row = ordertable.insertRow(1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    cell1.innerHTML = x[0];
    cell2.innerHTML = x[1];
    cell3.innerHTML = "<input type='button' value='Delete' class='deleteBtn'/>"
}

//Edit Function 
$(".editBtn").click(function(){
   console.log("Edit clicked");
});

//Delete Function
$(".deleteBtn").click(function(){
   console.log(productArray);
   var row = this.parentNode.parentNode;
   ordertable.deleteRow(row.rowIndex);//remove from the table
   productArray.splice(row.rowIndex);//remove from the order array
   console.log(productArray); 

});

//Confirm order Function
$(".confirmBtn").click(function(){
   console.log("Confirm clicked");
});

Currently I can successfully remove elements from the table. However when I try to remove the element from the array it removes the first element of the array

For example:

Array before delete

["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3", "SATO WHITE LABEL:2", "SATO INK PADS:1", "SATO GUN:2"] 

Array when delete is clicked once

["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3", "SATO WHITE LABEL:2", "SATO INK PADS:1"] 

Array when delete is clicked twice

["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3", "SATO WHITE LABEL:2"] 

Array when delete is clicked third time

["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3"] 

Array when delete is clicked fourth time

["EXCEL 5LB BLACK:2"] 

The code responsible for this is:

//Delete Function
$(".deleteBtn").click(function(){
   console.log(productArray);
   var row = this.parentNode.parentNode;
   ordertable.deleteRow(row.rowIndex);//remove from the table
   productArray.splice(row.rowIndex);//remove from the order array
   console.log(productArray); 

});

The idea is that the row to be removed from table is the same index as item to be removed from array but this is not working at the moment.

productArray.splice(row.rowIndex,1);

use this splice method to remove

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Just a suggestion: You don't need to worry about deleting both in the table and in the array if you use ng-repeat of angular.js

You forgot the howMany argument. That's how many to remove from the array.

array.splice(index , howMany)

So your code should look like

productArray.splice(row.rowIndex, 1);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

const candidates = [
  {
    name: "Amir",
    lastName: "Hoxha",
    email: "wow@gmail.com",
    phone: 198465,
  },
  {
    name: "geogre",
    lastName: "horhe",
    email: "Horhe@masvidal.com",
    phone: 694204,
  },
  {
    name: "Ali",
    lastName: "Hamdi",
    email: "Dragashi123@gmail.com",
    phone: 454784,
  },
];
const name = document.getElementById("name").value;
const lastName = document.getElementById("last-name").value;
const email = document.getElementById("email").value;
const phone = document.getElementById("phone").value;

bulidTable(candidates);

function bulidTable(data) {
  let myTable = document
    .getElementById("my-table")
    .getElementsByTagName("tbody")[0];

  myTable.innerHTML = "";

  for (let i = 0; i < data.length; i++) {
    var row = `<tr>
                    <td>${data[i].name}</td>
                    <td>${data[i].lastName}</td>
                    <td>${data[i].email}</td>
                    <td>${data[i].phone}</td>
                    <td><button id="btnDelete" >Delete</button>
                       <button id="btnEdit" onclick="editRow()">Edit</button>
                    </td>
                 </tr> `;
    myTable.innerHTML += row;
  }
}

const myTable = document
  .getElementById("my-table")
  .getElementsByTagName("tbody")[0];

function addRow() {
  // changeToAdd();
  if (!valditade()) {
    const name = document.getElementById("name").value;
    const lastName = document.getElementById("last-name").value;
    const email = document.getElementById("email").value;
    const phone = document.getElementById("phone").value;
    console.log(name, lastName, email, phone);

    const obj = {
      name: name,
      lastName: lastName,
      email: email,
      phone: phone,
    };

    candidates.push(obj);

    valditade();

    bulidTable(candidates);
  }
}

// const btnEdit = document.getElementById("btnEdit");
// console.log(btnEdit);
// The Delete Row function
addEventListener("click", (e) => {
  if (e.target.id === "btnDelete") {
    console.log(e.target.parentElement.parentElement);
    const indexToRemove = e.target.parentElement.parentElement.rowIndex - 1;
    candidates.splice(indexToRemove, 1);
  }
  bulidTable(candidates);
});

// The Edit Row function

const btnEdit = document.getElementById("my-button");
console.log(btnEdit);
const btnSave = document.getElementById("btnSave");
console.log(btnSave);

var table = document.getElementById("my-table");
var rIndex;
function editRow() {
  for (var i = 1; i < table.rows.length; i++) {
    table.rows[i].onclick = function () {
      rIndex = this.rowIndex;
      console.log(rIndex);

      document.getElementById("name").value = this.cells[0].innerHTML;
      document.getElementById("last-name").value = this.cells[1].innerHTML;
      document.getElementById("email").value = this.cells[2].innerHTML;
      document.getElementById("phone").value = this.cells[3].innerHTML;
    };

    document.getElementById("my-button").style.display = "none";
    document.getElementById("btnSave").style.display = "block";
  }
}

btnSave.addEventListener("click", (event) => {
  console.log(rIndex);
  console.log(candidates);

  const name = document.getElementById("name").value;
  const lastName = document.getElementById("last-name").value;
  const email = document.getElementById("email").value;
  const phone = document.getElementById("phone").value;

  for (var i = 0; i < candidates.length; i++) {
    if (i === rIndex - 1) {
      candidates[i].name = name;
      candidates[i].lastName = lastName;
      candidates[i].email = email;
      candidates[i].phone = phone;
    }
  }

  event.preventDefault();
  document.getElementById("my-button").style.display = "block";
  document.getElementById("btnSave").style.display = "none";

  console.log(name, lastName, email, phone);
  bulidTable(candidates);
});

// Function for clearing the inputs after the add button was clicked on

let btnClear = document.getElementById("my-button");
let inputs = document.querySelectorAll("input");

btnClear.addEventListener("click", () => {
  inputs.forEach((input) => (input.value = ""));
});

btnSave.addEventListener("click", () => {
  inputs.forEach((input) => (input.value = ""));
});

//This function makes sure that the user has enterted all the required information.
function valditade() {
  var isEmpty = false;
  const name = document.getElementById("name").value;
  const lastName = document.getElementById("last-name").value;
  const email = document.getElementById("email").value;
  const phone = document.getElementById("phone").value;

  if (name === "" && lastName === "" && email === "" && phone === "") {
    alert("You Left all the inputs empty");
    isEmpty = true;
  } else if (name === "") {
    alert("Please provide your name");
    isEmpty = true;
  } else if (lastName === "") {
    alert("Please Provide your last name");
    isEmpty = true;
  } else if (email === "") {
    alert("Please provide your Email");
    isEmpty = true;
  } else if (phone === "") {
    alert("Please provide your Phone number");
    isEmpty = true;
  }
  return isEmpty;
}
body {
  background: linear-gradient(to left, #333, #333 50%, #eee 75%, #333 75%);
}
table,
th,
td {
  font-family: Georgia, "Times New Roman", Times, serif;

}

table#my-table {
  border: 1px solid black;
  border-radius: 14px;
  border-spacing: 0;
}
table#my-table td,
table#my-table {
  border-bottom: 1px solid black;
  padding: 10px;
}
#table {
  margin: 5rem 31rem;
  color: white;
  font-size: 18px;

}

/* #my-table tr:nth-child(even){

} */
/* #my-table{
  border: 1px solid black;
  position: static;
  width: 20%;
} */

table#my-table tr:last-child > td {
  border-bottom: none;
}
#my-button {
  display: block;
  background-color: #b00b69;
  padding: 12px;
  font-size: 14px;
  color: white;
}
.btnSave{
  display: flex;
  justify-content: center;
  margin: 20px;
  padding-top: 15px;
}
#btnSave{
  display: none;
  background-color: #b00b69;
  padding: 12px;
  font-size: 14px;
  color: white;
}
#my-form {
  display: flex;
  justify-content: center;
  margin: 20px;
  padding-top: 15px;
}
#name,
#last-name,
#email,
#phone {
  margin: 5px;
  padding: 6px;
  border-radius: 5px;
  font-size: 14px;
}
#name:focus {
  background-color: #b00b69;
}
#last-name:focus {
  background-color: #b00b69;
}
#email:focus {
  background-color: #b00b69;
}
#phone:focus {
  background-color: #b00b69;
}
#btnDelete {
  color: white;
  background-color: black;
  padding: 8px;
  padding-right: 10px;
  margin-top: 5px;
}
#btnEdit {
  color: white;
  background-color: black;
  padding: 8px;
  padding-right: 25px;
  margin-top: 5px;
}
<!DOCTYPE html>
<html lang="en">
    <body>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Table </title>
    <link rel="styleSheet" href="style.css">
    <script src="table.js" defer></script>
</head>
<body>

    <form  id="my-form">
        <input type="text"  id="name"   required maxlength="8">
        <input type="text" id="last-name" required maxlength="8">
        <input type="text" id="email"   required maxlength="23" >
        <input type="number" id="phone" pattern="/^-?\d+\.?\d*$/" 
        onKeyPress="if(this.value.length == 9) return false;">
        <button id="my-button" onclick="addRow()"  value="Add">Add</button>
        <button id="btnSave">Save</button>
    </form>


 <div id="table">
    <table id="my-table">
       <thead> 
        <tr>
            <th>Name</th>
            <th>Last Name</th>
            <th>Email</th>
            <th>phone</th>
            <th>Action</th>
        </tr> 
        </thead>
        <tbody id="my-body">
    
         </tbody>
         </table>
 
</body>
</html>

**This is a table that is populated using an array of objects and i add new rows to the table using the push() method and i removed rows using the splice method() **

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