0

I have a javascript array called names[] which stores names. (ofcourse) The names are also stored in list items in my html document, I have this code that removes a name when you click on it;

$(document).ready(function(){
    $(document).on('click', 'li', function(){
        $(this).remove();
    });
});

Can anyone tell me how I remove the same item from the array names[]?

UPDATE: names[] is defined as follows:

function submit() {
    var theName = document.getElementById("enter").value;

    if (theName == "" || theName.length == 0) {
        return false;
    }

    names.push(theName);
    document.getElementById("name").children[0].innerHTML += "<li>" + names[names.length - 1] + "</li>";
    document.getElementById("enter").value = "";
}

This is done with an <input>.

3
  • 1
    Please show us how names is defined. Commented Feb 28, 2015 at 1:27
  • function submit() { var theName = document.getElementById("enter").value; if (theName == "" || theName.length == 0) { return false; } names.push(theName); document.getElementById("name").children[0].innerHTML += "<li>" + names[names.length - 1] + "</li>"; document.getElementById("enter").value = ""; } This is done with <input> Commented Feb 28, 2015 at 1:29
  • FYI, Next time you want to add details to your question, please add the edits to the actual post rather than putting them here in the comments. Commented Feb 28, 2015 at 5:10

1 Answer 1

1
Array.prototype.remove = function(item) {
    var index = this.indexOf(item);
    if (index > -1) {
        this.splice(index, 1);
        return true;
    }

    return false;
};    

$(document).ready(function(){
    $(document).on('click', 'li', function(){
        var text = $(this).text();
        names.remove(text);
        $(this).remove();
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

-edit I accidently pressed a button, it does work, thanks, but a explanation would be nice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.