philecker
philecker

Reputation: 49

jQuery .inArray If/Else Always Returning -1

I have a function that I'm trying to check if a value exists already. However even though values exist it's still returning -1. I'm trying to get my if/else statement working that if an item exists it "alerts" and if doesn't it runs the function addItem();

$(".detail-view button").on("click", function () {
    itemExists();

    function itemExists() {
        var detailID = $(this).attr('id');
        var itemArr = [];
        $("input#lunchorder_item_entry_id").each(function (index) {
            var lunchItemID = $(this).val();

            itemArr.push(lunchItemID);
        });

        addItem();

        alert(jQuery.inArray(detailID, itemArr));

        /*
        if (jQuery.inArray(detailID, itemArr)) {
            alert("You have already added this item. If you want to change item details, please remove the item and re-add it to your cart. Thank You!");
        } else {
            // the element is not in the array
            addItem();
        } */

        console.log(itemArr);
    }

Upvotes: 0

Views: 235

Answers (2)

Bergi
Bergi

Reputation: 664217

However even though values exist it's still returning -1

I don't know how to proof that since you didn't provide any sample input. Yet, in the way your are calling itemExists the this keyword is undefined/window, and $(this).attr('id') probably results undefined.

To fix that, either use itemExists.call(this) or store the DOM element (or even $(this)?) in a local variable and use that, or even move itemExists outside your handler and invoke it with explicit arguments.

I'm trying to get my if/else statement working that if an item exists…

As you noticed, the returned index is -1. That means to check whether an element is contained in the array you will need to compare against -1, not cast every non-zero number to true:

if (jQuery.inArray(detailID, itemArr) != -1)

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

This is because detailID and itemArr are local to the function itemExists() and is undefined where your if condition is.

Moving it outside, should fix it.

...
var detailID = $(this).attr('id'); 
var itemArr = [];
function itemExists() {
   ...
}
...

Upvotes: 1

Related Questions