Search code examples
javascriptjqueryarrayssplice

Function runs twice after click


I am currently working on a project that utilizes an input to create a list of items. I have the addition of programs working, however the deletion of an item is where I am having problems. The items are added to an array via .push() and the method of deletion is via the .splice() method. The function correctly splices the correct array element but ends up doing a second pass and deleting the elements before it. How do I stop the splice from happening more than once?

$(skill_add_button).click(function(e){ //on add input button click
        var skill_input=document.getElementById("skill_input").value;
        document.getElementById("skill_input").value = "";
        e.preventDefault();
        if(s < 12){ //max input box allowed
            if (skill_input==""){
                skillset = skill_arr.join('');
                alert(skillset);
            } else {
                s++; //text box increment
                $(skill_wrap).append('<div class="skill_tag" id="skill_tag'+s+'">'+skill_input+'</div>'); //add input box
                skill_arr.push(skill_input+'|s|');

                alert(skill_arr);
                $('.skill_tag').hover(function(){
                        $(this).css("background-color", "#C14330");
                        $(this).css("cursor", "pointer");
                        }, function(){
                        $(this).css("background-color", "#04CA29");
                    });
                $('.skill_tag').click(function() {
                    var skill_id = $(this).attr('id');
                    var index = skill_id.split('skill_tag').pop();
                    skill_arr.splice(index,1);
                    $('#'+skill_id).remove();
                    alert(skill_arr);
                    s--;
                });
            }
        } 
        if(s > 11) {
                $(skill_add_button).remove();
         }
    });

If I try to put my .skill_tag click function outside of my skill_add_function, it does not work at all.


Solution

  • Each time you click on $(skill_add_button) you create a new div.skill_tag but and you add .click event on ALL .skill_tag elements of the page.

    Save your generated div into a var and use this var to add click event.

    var myDiv = '<div class="skill_tag" id="skill_tag'+s+'">'+skill_input+'</div>';
    $(skill_wrap).append(myDiv); //add input box
    [...]
    myDiv.hover(function(){
    [...]
    myDiv.click(function(){