Thursday, 22 September 2011

Dynamically generate HTML OPTGROUP from XML





//XML RETURN FROM WEBSERVICE
<Types total="4"><Type><TypeId>1</TypeId><TypeName>Mobile</TypeName><Categories total="2"><Category><CategoryId>1</CategoryId><CategoryName>iPhone</CategoryName></Category><Category><CategoryId>2</CategoryId><CategoryName>Android</CategoryName></Category></Categories></Type><Type><TypeId>2</TypeId><TypeName>Songs</TypeName><Categories total="1"><Category><CategoryId>220</CategoryId><CategoryName>Bhag Dk Bose</CategoryName></Category></Categories></Type><Type><TypeId>3</TypeId><TypeName>Movies</TypeName><Categories total="5"><Category><CategoryId>3</CategoryId><CategoryName>FALTU</CategoryName></Category><Category><CategoryId>4</CategoryId><CategoryName>DELHI BELLY</CategoryName></Category><Category><CategoryId>5</CategoryId><CategoryName>TITANIC</CategoryName></Category><Category><CategoryId>6</CategoryId><CategoryName>HANGOVER</CategoryName></Category><Category><CategoryId>7</CategoryId><CategoryName>MAX PAYNE</CategoryName></Category></Categories></Type><Type><TypeId>4</TypeId><TypeName>GAMES</TypeName><Categories total="2"><Category><CategoryId>25</CategoryId><CategoryName>ANGRY BIRDS</CategoryName></Category><Category><CategoryId>26</CategoryId><CategoryName>COUNTER-STRIKE</CategoryName></Category></Categories></Type></Types></Response>

//AJAX REQUEST
URI-> PATH of webservice 
method--> method name of webservice
I/p-> method expected

  $.ajax({
    cache: false,
    type: 'POST',
    url: URI,
  
   data: {
   method : "" , 
   I/P Parameters:""
   },
   
   beforeSend:function(msg){
  
   },
   success: function(msg) {
     
       $(msg).find("Response").each(function() {
      
                    $(this).parent().find("Types").each(function(){
                var optGrp;
                $(this).find("Type").each(function(){
                   optGrp = document.createElement("optgroup");
                   optGrp.label = $(this).find("TypeName").text();
document.getElementById("categoryTextField").appendChild(optGrp); // THIS line add optgroup to your field.

If any Label you removed then this piece of code works.
//FOR REMOVING 2 ID into my id=categorytextField 
      if($(this).find("TypeId").text() != 2){
      document.getElementById("categoryTextField").appendChild(optGrp);
}
       $(this).find("Categories").each(function(){
                 $(this).find("Category").each(function(){
               
              var option = document.createElement("option");
             option.value=$(this).find("CategoryId").text();
             option.text=$(this).find("CategoryName").text();
             optGrp.appendChild(option);
             });
       }); 
       
      });
   });
      
  },
    error: function(msg) {
    },
    complete:function(msg) {
    
    }
    
   });



cheers :)


No comments:

Post a Comment