Reputation: 11
I am trying to delete whole data of one person from the array when you click on the delete button but it is not working. please help.
var data = [ {name: 'Peter', lastName: 'Petterson', dob: '13/12/1988'},
{name: 'Anna', lastName: 'Jones', dob: '06/02/1968'},
{name: 'John', lastName: 'Milton', dob: '01/06/2000'},
{name: 'James', lastName: 'White', dob: '30/11/1970'},
{name: 'Luke', lastName: 'Brown', dob: '15/08/1999'}
];
var names = data.map(function(x,i){
var myNames = document.getElementById('name');
myNames.innerHTML += (i +". "+ x.name + ' '+x.lastName +" "+ "<button onclick = fun("+i+")>DEL</button>"+'<br>');;
});
function fun(num){
data.splice(num,1);
}
<div id='name'></div>
Upvotes: 1
Views: 907
Reputation: 67525
You could wrap you entry on span
like :
myNames.innerHTML += "<span>"+(i +". "+ x.name + ' '+x.lastName +" <button onclick=fun(this,"+i+")>DEL</button><br></span>");
Then pass also the current clicked button this
on click as parameter :
<button onclick=fun(this,"+i+")>DEL</button>
And use the closest()
method to get the parent span
then remove it from the DOM usind remove()
method.
NOTE : Better to use forEach
instead of map
.
var data = [ {name: 'Peter', lastName: 'Petterson', dob: '13/12/1988'},
{name: 'Anna', lastName: 'Jones', dob: '06/02/1968'},
{name: 'John', lastName: 'Milton', dob: '01/06/2000'},
{name: 'James', lastName: 'White', dob: '30/11/1970'},
{name: 'Luke', lastName: 'Brown', dob: '15/08/1999'}
];
var myNames = document.getElementById('name');
data.forEach(function(x,i){
myNames.innerHTML += "<span>"+(i +". "+ x.name + ' '+x.lastName +" <button onclick=fun(this,"+i+")>DEL</button><br></span>");
});
function fun(_current_button,num){
data.splice(num,1);
_current_button.closest('span').remove();
}
<div id='name'></div>
Upvotes: 2
Reputation: 67525
Problem : You're removing the object just from the array not from the DOM.
Suggested solution : You should update the DOM so I suggest to wrap the innerHTML
part in another function then call it everytime you're updating the data
so you could see the remove reflection on the page :
function showData(){
myNames.innerHTML ='';
data.map(function(x,i){
myNames.innerHTML += (i +". "+ x.name + ' '+x.lastName +" "+ "<button onclick = fun("+i+")>DEL</button>"+'<br>');
});
}
Hope this helps.
var myNames = document.getElementById('name');
var data = [ {name: 'Peter', lastName: 'Petterson', dob: '13/12/1988'},
{name: 'Anna', lastName: 'Jones', dob: '06/02/1968'},
{name: 'John', lastName: 'Milton', dob: '01/06/2000'},
{name: 'James', lastName: 'White', dob: '30/11/1970'},
{name: 'Luke', lastName: 'Brown', dob: '15/08/1999'}
];
showData();
function showData(){
myNames.innerHTML ='';
data.map(function(x,i){
myNames.innerHTML += (i +". "+ x.name + ' '+x.lastName +" "+ "<button onclick = fun("+i+")>DEL</button>"+'<br>');
});
}
function fun(num){
data.splice(num,1);
showData();
}
<div id='name'></div>
Upvotes: 1