user3450590
user3450590

Reputation: 341

removing a value from array

I am working on a dropdown list which contains a checkbox and a value. When i select a checkbox, the id of that perticular item is appended to a input on right panel and the value of that item gets appended in the form of a tag on the right panel. When i click again on a checked checkbox, the appended value and the tag on the right have to be removed.

The problem i am facing is that the checkbox i am unchecking is not getting removed, instead some other alread appended value is getting removed.

Javascript:

var arr = [];
$(".taglistarea input[type='text']").click(function(){
    if(!$(this).parent("div").next(".taglist").is(":visible")) {
        $(this).parent("div").next(".taglist").slideDown();
    } else {
        $(this).parent("div").next(".taglist").slideUp();
    }
});

$(".taglist ul li a input[type='checkbox']").click(function(){
    var tagidall = $(".taglist ul li a").attr("id");

    var tagideach = $(this).parent("a").attr("id");
    var tagtexteach = $(this).text();

    arr.push(tagideach);

    if($(this).is(":checked")) {
        $(this).addClass("active");
        $(".ss").append('<a href="#" id="'+tagideach+'" class="tagss">International<span class="closetag"></span></a>');    
    } else {
        $(".ss a[id="+tagideach+"]").remove();
        //arr.splice(tagideach,1);
    }
    //alert(arr);
    $("#idvals").val(arr.toString());
});

i think that problem is here:

arr.splice(tagideach,1);

the complete fiddle is here: https://jsfiddle.net/kue83ud8/

Thanks.

Upvotes: 2

Views: 225

Answers (2)

Azad
Azad

Reputation: 5264

set element index to remove from array

arr.splice(arr.indexOf(tagideach),1);

Upvotes: 1

pwolaq
pwolaq

Reputation: 6381

as you said, the problem is with arr.splice(tagideach,1);

first argument of splice is the index to remove, not an object

you should replace that line with arr.splice(arr.indexOf(tagideach),1); (you should also check if indexOf returns value other than -1

another remarks

you should cache your selectors to improve performance:

if(!$(this).parent("div").next(".taglist").is(":visible")) {
    $(this).parent("div").next(".taglist").slideDown();
} else {
    $(this).parent("div").next(".taglist").slideUp();
}

should become:

var element = $(this).parent("div").next(".taglist");
if(!element.is(":visible")) {
    element.slideDown();
} else {
    element.slideUp();
}

instead of checking if element is visible you can use slideToggle()

also, you should read about event delegation in jQuery

Upvotes: 3

Related Questions