1

I have 4 <select> boxes with the same values:

  • 1
  • 2
  • 3
  • 4

I wish to make sure each of these values are used in the dropdowns, with no duplicates.

I can not get my head around this. I have tried looping the select boxes and picking out the values, but I can not get it to work probably. Does anyone have a quick-n-easy solution to this?

janhartmann
  • 14,713
  • 15
  • 82
  • 138

2 Answers2

2

Get the unique value list then check the length with the original array.

var arr = [1,2,3,4];

if ($.unique($('select').map(function(){ return $(this).val(); })).length === arr.length) {
   // OK
}
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Lets say I added a another value "-1" (e.g. used for "Choose value"), can this still be used? – janhartmann Mar 12 '14 at 14:13
  • Got it to work by checking for -1 before returning the .val(). Used "return;" - is this OK? ;-) – janhartmann Mar 12 '14 at 14:39
  • @xdazz could you explain this a bit, it appears https://api.jquery.com/jQuery.unique/ only works for DOM elements. The result of the map of selects returns an array of numbers. Also see OP's follow up question which confirms the unique issue http://stackoverflow.com/questions/22356314/ensure-all-values-are-used – Huangism Mar 12 '14 at 16:15
0

My solution to this problem

HTML

<select id="sselect"></select>

JavaScript

var a = [1,2,2,3,4,5];
var duplicates = a;
var result = [];
$(function() {
    for ( var i = 0; i < a.length; i++) {
       var item = a[i];
    for ( var c = 0; c < duplicates.length; c++) {
          if (jQuery.inArray(item, result) == -1) {
         result.push(item);
        }
    }
}
});

for ( var i = 0; i < result.length; i++) {
 $('#sselect').append($('<option>', { 
        value: result[i],
        text : result[i] 
    }));
}

Live example of this code

Игор
  • 355
  • 3
  • 10
  • 24