Reputation: 147
I have a select2 dropdown on my page that is populated with countries from a table in my database. A user is able to select more than one country, forming an array. I want to search for two values in the array. For example:
var selvalues = $(this).val(); //["AS", "US", "CA"]
On the change event of the dropwdown, If "US" is one of the values and the array also contains a value that is not the "US", throw an error.
Some of the things that I have tried so far in jQuery:
$('#countriesSelect').on('change', function(){
var selvalues = $(this).val();
console.log(selvalues .some(x => x !== 'US' && x == 'US'));
if(selvalues.includes('US') || !selvalues.includes('US')){
console.log('You cannot choose a foreign country when current selection is US');
}
if($.inArray("US",selvalues) != -1){
$('#usregions').show().fadeIn();
if($.inArray("US",selvalues) != -1){}
} else {
$('#usregions').hide().fadeOut();
}
$.each(selvalues, function( index, value ) {
console.log()
if(value == 'US' && value != 'US'){
console.log('You cannot choose a foreign country when current selection is US');
}
});
});
I expect to have it to throw an error based on the above criteria.
Upvotes: 0
Views: 61
Reputation: 24965
Work the logic. It's an error if you select US
and something else. Meaning you have at least two selections, one of which being US
. So you do not care what the others are, so long as there are multiple and one is the US
.
if (selvalues.length > 1 && selvalues.includes('US')) { ...problem... }
Upvotes: 2