javascript - JS Array Splice to remove an element in an Array -
i have table being populated array containing list of products , quantities order placed customer. on order confirmation screen user can remove items in order clicking delete
button associated particular row
.
this html
<div id="summary"> <table id="ordertable"> <tr><th>product</th> <th>quantity</th> <th></th> </tr> </table> </div>
this 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 array for(i = 0; < productarray.length; ++){ 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 table productarray.splice(row.rowindex);//remove order array console.log(productarray); }); //confirm order function $(".confirmbtn").click(function(){ console.log("confirm clicked"); });
currently can remove elements table. when try remove element array
removes first element of 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 clicked once
["excel 5lb black:2", "excel 5lb black:3", "sato white label:2", "sato ink pads:1"]
array when delete clicked twice
["excel 5lb black:2", "excel 5lb black:3", "sato white label:2"]
array when delete clicked third time
["excel 5lb black:2", "excel 5lb black:3"]
array when delete clicked fourth time
["excel 5lb black:2"]
the code responsible is:
//delete function $(".deletebtn").click(function(){ console.log(productarray); var row = this.parentnode.parentnode; ordertable.deleterow(row.rowindex);//remove table productarray.splice(row.rowindex);//remove order array console.log(productarray); });
the idea row removed table same index
item removed array
not working @ moment.
productarray.splice(row.rowindex,1);
use splice method remove
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/splice
just suggestion: don't need worry deleting both in table , in array if use ng-repeat of angular.js
Comments
Post a Comment