2

I'm trying to set up a set of select boxes to quickly filter fairly large datasets into usable chunks. And I'm very close, but receiving the exact opposite of the solution I want, whether or not I use .not() selector (or take it out), or set up the call using .attr= (or .attr!=).

Here's a fiddle so you can see what's going on:

http://jsfiddle.net/yD5cG/3/ (Ignore the fact that once you change the top-level selection, the bottom select box doesn't change. I won't need to worry about this).

I've trawled the site and found a lot of code that's close to what I need, but I think parsing arrays is throwing it off? At this point, I can't tell if I'm over-complicating things or over-simplifying. (This is basically an attempt at a simple many-to-many filter using JQuery).

Thanks for anything, even the most basic idea...

dilettante
  • 381
  • 1
  • 4
  • 19
  • All those invalid attributes are not needed; see answer below. – iambriansreed May 05 '12 at 01:50
  • 1
    Thanks @iambriansreed! This is so simple and elegant-- to think, all those invalid attributes took me 4 hours to (nearly) figure out! The only problem is in my original markup, you'll see that one of the options in selectbox2 also contains two values. This is why I was creating attributes; I didn't think I could do it with option values. Going to see if I can use your code as a springboard to make this work. – dilettante May 05 '12 at 02:26
  • Updated to work with options with *multiple* values. Fiddle updated. Remember to vote up and accept. :) – iambriansreed May 05 '12 at 02:54
  • Works beautifully and I understand it perfectly. Thanks for the whistle-clean code. – dilettante May 05 '12 at 14:07

1 Answers1

2

Proof: http://jsfiddle.net/iambriansreed/KBKEV/

var options = $('#selectbox2').html();
//store original options
$("#selectbox1").change(function() {
    var selected = this.value.split(',');
    // get selected value and make it an array
    $('#selectbox2').html(options);
    // reset the box to the original options
    $('#selectbox2 option').filter(function(){
        if(this.value.indexOf(',') == -1){
            // simple single values
            return $.inArray(this.value, selected) == -1;
        }else{  
            // check each value
            var values = this.value.split(',');
            for(i in values){
                if($.inArray(values[i], selected) > -1)
                    return false;            
            }
            return true;  
        }  
    }).remove();    
    // remove any options not in the array of selected values
});​

A working fiddle and a step by step explanation. Another quality answer.

iambriansreed
  • 21,935
  • 6
  • 63
  • 79