Reputation: 274
I have a table with few rows and delete button. I have stored all the list of table in an array 'arr'. How can I remove the selected item from that array on button click.
<table id="sum_table">
<tr class="titlerow">
<th>S.N.</th>
<th>Name</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>John</td>
<td><button class="dm" data-id="0">Remove</button></td>
</tr>
<tr>
<td>2</td>
<td>Henry</td>
<td><button class="dm" data-id="1">Remove</button></td>
</tr>
</table>
var arr= [
["name", John],
["name", Henry]
];
function clickHandler(clickEvent) {
}
document.addEventListener('DOMContentLoaded', function() {
document.addEventListener('click', clickHandler);
});
Upvotes: 2
Views: 13306
Reputation: 7030
Lets say you send the name of the person on click event then you can use array.splice
method as shown below :
for(var i = arr.length - 1; i >= 0; i--) {
if(arr[i] === name) {
arr.splice(i, 1);
}
}
You have to note that it will delete all the values from array which has the same name.
With Index - Just send the data-id on click of button and splice the array on that index
arr.splice(dataid, 1)
Upvotes: 0
Reputation: 281794
Your array need to be an array of object and not an array of array. Also you can give a class to the name column of a table to access its value and then use findIndex
to find the index of the name attribute in array and then splice
to remove it.
$(function(){
var arr= [
{"name": "John"},
{"name": "Henry"}
];
$('.dm').click(function(){
var val = $(this).closest('tr').find(".name").text();
console.log(val);
var index = arr.findIndex(function(item) {return item.name == val})
console.log(index)
arr.splice(index, 1)
console.log(arr);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="sum_table">
<tr class="titlerow">
<th>S.N.</th>
<th>Name</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td class="name">John</td>
<td><button class="dm" data-id="0">Remove</button></td>
</tr>
<tr>
<td>2</td>
<td class="name">Henry</td>
<td><button class="dm" data-id="1">Remove</button></td>
</tr>
</table>
Upvotes: 1