views:

185

answers:

2

This is a problem I'm having in actionscript, but just as easily applies to Javascript or Jquery. Basically, I have 3 select boxes, e.g.:

<select id="color">
 <option>Red</option>
 <option>Blue</option>
 <option>Green</option>
</select>
<select id="size">
 <option>1</option>
 <option>2</option>
 <option>3</option>
</select>
<select id="type">
 <option>A</option>
 <option>B</option>
 <option>C</option>
</select>

When a color is chosen - I want the size and type to filter out only those which are available for that color. Further, when a user then chooses a size, the type should reduce further, and the color should also be filtered according to the size.

I've been wrestling with this problem for awhile, and have yet to find an elegant solution for it. Does anybody have any clues for an approach?

+1  A: 
// Assuming this is some kind of store, with items with different capabilities.

var data = [{id:"item1", color:"red", size:1, type:"A"}, 
{id:"item2", color:"red", size:2, type:"B"}, 
{id:"item3", color:"blue", size:3, type:"C"}, 
{id:"item4", color:"green", size:3, type:"C"}];

$('select#color').change(function(e){

var value = $(this).val();
var sizes = [];
var types = [];

$.each(data, function(i, val) {

if (val.color == value) {

// only add options once
if (!sizes.indexOf(val.size)
sizes.push(val.size);

if (!sizes.indexOf(val.type)
types.push(val.type);


}

});



// now you would have arrays with all the available options, 
// which you could then use to render the select options.


// since I don't know about the exact usage this may or may not be optimal 
// in your case.
// it's not a complete solution, but may help to get you started.
sandstrom
Trying this now...
majman
This solution doesn't get me as far as I had hoped. Things are more complicated in the data, where items are more like: {id:"item1", color:["red", "blue"], size:[1, 2, 3], type:"A"}for example...
majman
+1  A: 
  1. Populate 2 structures, one mapping color to array of avialable sizes, one mapping color/size combination (the key is color+"."+size) to array of avialable types.

    NOTE: You can do it with 1 nested structure, choose your preference. Then the list of sizes per color is a list of keys in sub-structure for that color.

  2. Have JavaScript populate the selects via onSelect handler.

Good tutorials on this are:

One select

Two selects (closer to what you want)

DVK
The second link only shows me an example with 2 select boxes, and does so in a linear order which would make things much easier. However, in my case, I need to be able to choose from any of 3 different select boxes which filters the 2 not chosen down.
majman