Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a type of newsfeed wall like Facebook were you can create posts. I want when I click on the glyphicon in my post to remove that certain post.

The code is:

function loadPosts(){
    $('#allPosts').empty();
    for (var i = 0; i < aPosts.length; i++){
        var postData = aPosts[i];
        var comments ="";
        for (var j = 0; j < postData.comments.length; j++ )
        {
            comments += '<p class="myComment">' + postData.comments[j].from + '<strong>says: </strong>'+ postData.comments[j].text +'</p>';
        }
        $('#allPosts').prepend('<div data-postId="'+i+'"class="wrapPost"><span class="glyphicon glyphicon-remove"></span>'  +
            postData.from +' '+''  +
            '<strong>wrote :</strong>'+
            '<li>' + postData.text + '</li>' + comments +
            '<input type=text class=commentBox placeholder=Comment..>' +
            '<button data-postId="'+i+'" class="postComment">Post</button></div>');

        $('.glyphicon-remove').click(function() {
            var postId = $(this).parent().attr('data-postId');
            console.log(postId);
            aPosts.splice(i, 1);

        });
    }
}

When I console log "postId" it tells me that I am at least clicking the right post, but it wont delete it from localStorage.

share|improve this question
    
So anyone can delete any post if they start messing with the IDs? –  Jonathan Oct 2 at 7:52
    
It's personal project, so yeah anyone can delete posts. –  Smári Alfreðsson Oct 2 at 7:54
    
If you change aPosts.splice(i, 1); to aPosts.splice(parseInt(postId), 1); does that help? I would also take the click event definition out of the for loop. –  mccannf Oct 2 at 8:02
    
Hi @mccannf - Thank you for the suggestion but it's not working unfortunately. –  Smári Alfreðsson Oct 2 at 8:05
    
You are attaching click handlers every time in the foreach. Take it out of the foreach. And you need to manually tell jQuery to .remove() the icon's parent that was clicked. –  DOC ASAREL Oct 2 at 8:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.