Javascript - remove specific element from dynamically generated array

I have a page where users can create tags (like here on stackoverflow) that are then POST to the back end for storage in the database. The user can create tags as well as delete them before finally clicking "Submit".

In the DOM, tags are generated along with the "x" button. The "x" button removes the element from the DOM, but the problem occurs when removing from the array. The closest I could solve was this question , however I could not get it to work for me.

Here's the codepen

Here's the javascript (I am using JQuery)

window.tag_array = [];

$( "#addtag" ).click(function() {

var tag = $("#input-tag").val();

//if tag is empty
if(!$('#input-tag').val()) {

    alert("can't be empty");

    } else {
        //put tag.val into an array         
        tag_array.push(tag);

        //add to DOM
        $( "#tagsbox" )
        .append( "<div class='displaytag'><i>"+tag+"</i><input type='hidden' class='tag' value="+tag+"><button onClick='return false;' class='removetag'>x</button></div>" );

        //reset value in text area to null
        $("#input-tag").val("");

        //remove tag onclick
        $('.removetag').click(function() {
            $(this).parent().remove(); //remove tag from DOM

            //splice from array
            tag_array.splice( this, 1 ); //<--HERE IS PROBLEM (i think)

        });


    } //end else

    alert(tag_array); //check array
});

      

The end result is splicing too many array elements.

I have also tried

tag_array.splice(tag_array.indexOf(tag),1);

      

to a similar result.

Please, help! thanks in advance

+3


source to share


2 answers


You should probably use smth, for example .indexOf()

, to enter the index of the element elem and then splicing the array

tag_array.splice(tag_array.indexOf(elm),1);

      



Working demo

+2


source


Part splice

is fine. The problem is you are adding the click callback to .removetag

too many times.

Every time you add a new element, you add a different event click

to every element .removetag

that is already on the page.

$('.removetag').click(function()

      

This way, whenever you click on one item, the callbacks were also assigned to everyone else.



Decision

Instead, when creating the tag, only set the click event on the last added element .removetag

:

$('.removetag').last().click(function()

      

Updated by CODEPEN

+2


source







All Articles