htmljsonhtml-selectmootools

mootools JSON to select list


I have a JSON object:

    var data = {"options" :[      
       {"name": "Size",  "value": "S", "price": "10", "order": "1"},
       {"name": "Size",  "value": "M", "price": "12", "order": "2"},
       {"name": "Size",  "value": "XL", "price": "14", "order":"3"},
       {"name": "Color", "value": "Red", "price": "14", "order":"2"},    
       {"name": "Color", "value": "Green", "price": "12", "order": "1"}
    ]}

How can I convert this to select list using mootools javascript library?

<div>
 <label>Size:</label>
 <select name="options[size]">
   <option value="10">S</option>
   <option value="12">M</option>
   <option value="14">XL</option>
 </select>
 <label>Color:</label>
 <select name="options[color]">
   <option value="12">Green</option>
   <option value="14">Red</option>
 </select>
</div>

Thanks!


Solution

  • It's just playing with the data a little bit - there you go: http://jsfiddle.net/XRH6r/

    var data = {"options" :[      
           {"name": "Size",  "value": "S", "price": "10", "order": "1"},
           {"name": "Size",  "value": "M", "price": "12", "order": "2"},
           {"name": "Size",  "value": "XL", "price": "14", "order":"3"},
           {"name": "Color", "value": "Red", "price": "14", "order":"2"},    
           {"name": "Color", "value": "Green", "price": "12", "order": "1"}
        ]};
    
    //create unique map according to the data:
    var arr = data.options;
    var map = {};
    arr.each(function(item){
        var name = item.name;
        var o;
        if(map[name]){
           o = map[name];      
        }
        else{
            o = {};
            o.options = [];
            map[name] = o;
        }
      o.options.push({value:item.value,price:item.price,order:Number(item.order)});
    });
    
    //sort options array to be ordered by order
    //and then build the select
    Object.each(map,function(item,name){
        item.options.sort(function(a,b){
               return a.order > b.order;
        });
        var label = new Element('label').set('html',name);
        var combo = new Element('select');
        item.options.each(function(opt){
           combo.options[combo.options.length] = new Option(opt.value,opt.price);     
        });
    
        label.inject(document.body);
        combo.inject(document.body);
    });