Create optgroup element into select list with DOM

 

今天在研究使用 Ajax 透過 jQuery 動態建立 Optgroup 清單。
混沌兩個月,終於寫出稍微有用的文章了…

JavaScript

  1. var obj = document.getElementById("list");
  2.  
  3. $.getJSON("ajax.asp", {id: idx}, function(json){
  4.  
  5.   // if json data created...
  6.   if(json.length > 0) {
  7.  
  8.     // get json data of optgroup
  9.     for(var i=0; i<json .length; i++) {
  10.       var oGroup = document.createElement("optgroup");
  11.       // setting label attribute
  12.       oGroup.label = json[i].title;
  13.       // insert optgroup element to select list
  14.       obj.appendChild(oGroup);
  15.  
  16.       // get json data of option
  17.       for(var j=0; j<json[i].product.length; j++) {
  18.         oOption = document.createElement("option");
  19.         //setting title attribute
  20.         oOption.label = "Option1";
  21.         //setting value attribute
  22.         oOption.value = "Value of Option1";
  23.         //insert option element to select list
  24.         obj.appendChild(oOption);
  25.       }
  26.     }
  27.   }
  28. });

JSON Data Example

  1. [
  2.    {
  3.       title:'optgroup1',
  4.       product:[
  5.          {
  6.             id:1,
  7.             title:'Demo1',
  8.             price:100
  9.          },
  10.          {
  11.             id:2,
  12.             title:'Demo2',
  13.             price:200
  14.          }
  15.       ]
  16.    },
  17.    {
  18.       title:'optgroup2',
  19.       product:{
  20.          id:3,
  21.          title:'Demo3',
  22.          price:300
  23.       }
  24.    }
  25. ]

Reference

Technorati Tags: , ,

回首過往今日

相關文章

No Comments yet »

本篇文章的迴響 RSS 訂閱。 TrackBack URI

發表迴響

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by WordPress with GimpStyle Theme design by Horacio Bella.
Entries and comments feeds. Valid XHTML and CSS.