简体   繁体   中英

Append only if item doesn't exists in array

I have 3 select boxes, one for country, another for cities and another one for radius around a city.

I want whatever the user choses to appear in a div before sending and saving all data in db.

I'm trying to make this work, but I dont know why I'm having strange results. It does nothing!, but if I remove the " ! " it kinda works for the first one , but then i get duplicates again. I dont understand what am i doing wrong. Here is the code:

var citySet = new Array;
function appendCity(){                  

    if(!$.inArray($("#businessCityTarget option:selected").text(),citySet)){                            

        $("#cityContainer").append($("#businessCityTarget option:selected").text() + "<br>"); 
        citySet.push($("#businessCityTarget option:selected").text());  

    }

}

Any light shed will be gratfull

Try:

if(citySet.indexOf($("#businessCityTarget option:selected").text()) < 0){
    $("#cityContainer").append($("#businessCityTarget option:selected").text() + "<br>"); 
    citySet.push($("#businessCityTarget option:selected").text());
}

can you try this:

var citySet = new Array;
function appendCity(){                  

        if($.inArray($("#businessCityTarget option:selected").text(),citySet)===-1){                            

            $("#cityContainer").append($("#businessCityTarget option:selected").text() + "<br>"); 
            citySet.push($("#businessCityTarget option:selected").text());  

        }

    }

Hope this helps..

You should check === -1 or < 0

var citySet = new Array;

function appendCity() {
    if ($.inArray($("#businessCityTarget option:selected").text(), citySet) === -1) {
        $("#cityContainer").append($("#businessCityTarget option:selected").text() + "<br>");
        citySet.push($("#businessCityTarget option:selected").text());
    }
}

From docs

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM