0

I have this function

function initRegion(region) {
    $.get( "/checkout/county", function( data ) {
        $(region).each(function(){
            var currentRegion = $(this);
            var previousValue = currentRegion.data('value');
            $.each(data, function (i, variable) {
                var option = $('<option>', {value: variable, text: variable});
                if(previousValue == variable){
                    option.prop('selected', true);
                }
                  currentRegion.append(option);
            });
       });
    });
    region.select2();
}

I want to check if "option" already exists in list before appending it, and if it doesn't then append it to list. How can I check that?

andy
  • 61
  • 6
  • What defines the "existence"? Same value? Same text? Same value and text? – Andreas May 12 '20 at 08:46
  • 1
    Does this answer your question? [Is there an "exists" function for jQuery?](https://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – freedomn-m May 12 '20 at 09:04
  • 1
    `currentRegion.find("option[value='" + variable + "']").length !== 0` – freedomn-m May 12 '20 at 09:06
  • I don't understand your question. You're creating a new `option` using "variable" as the value and text and want to check if that option already "exists" - well it will exist if there's an existing option that has text/value that matches "variable" - so why would you "use" anything else? **It's *your* variable name**. – freedomn-m May 12 '20 at 10:13
  • @freedomn-m ok, got It, thank you :) – andy May 12 '20 at 10:25

0 Answers0