Dynamically Creating a Select Box

dropdown-event1
This section is continued from previous section. Select box will be generated as being triggered.
dynamic-combo1

Summarized as three steps:

  1. Javascript function takes two parameters (list of JSON object and ID for select box)
  2. The function clear the select box to be re-constructed
  3. HTML Option tag is created one by one (key and value)

1. Javascript function takes two parameters (list of JSON object and ID for select box)

   $.ajax({
      type : "Get", 
      url : "onChangeTpCdRsnMain01",
      dataType: 'json',
      data : "tpCd=" + tpCd,
      success : function(data) {
         refreshCombo(data, "idSelectRsnCd");
      },
      error : function(e) {
         alert("error:" +response+ ":" +e);
      }
   });

Step 1.1. At line 7, the function call with parameters:

  1. A list of JSON object
  2. [
       Reason Code:001, Name:Item Damaged, Type:02, 
       Reason Code:003, Name:Customer has moved, Type:02, 
       Reason Code:004, Name:Cancelled by customer, Type:02, 
       Reason Code:011, Name:Wrong address, Type:02
    ]
    
  3. ID for a select box
  4. “idSelectRsnCd”


2. The function clear the select box to be re-constructed

function refreshCombo(dataList, comboId) {
   // Remove all current itmes
   $("#"+ comboId).children('option:not(:first)').remove();
   $.each(dataList, function(k, v) {
      // Get each key and value from the list
      var code = v.rtrnRsnCd;
      var val = v.rtrnRsnNm;
      $("#"+ comboId)
         // Set the key and value
         .append($("<option></option>")
         .attr("value",code)
         .text(val)
      );
   });
}

Step 2.1. At line 3, the select box with ID “idSelectRsnCd” is cleared
Step 2.2. At line 6 and 7, inside a loop, get key and value


3. HTML Option tag is created one by one (key and value)

function refreshCombo(dataList, comboId) {
   // Remove all current itmes
   $("#"+ comboId).children('option:not(:first)').remove();
   $.each(dataList, function(k, v) {
      // Get each key and value from the list
      var code = v.rtrnRsnCd;
      var val = v.rtrnRsnNm;
      $("#"+ comboId)
         // Set the key and value
         .append($("<option></option>")
         .attr("value",code)
         .text(val)
      );
   });
}

Step 3.1. At line 10 to 12, inside the loop, constructing HTML by setting the new value and key
Step 3.2. At line 8, the new HTML (with Option tag) is set to the ID “idSelectRsnCd

<form:select path="rtrnRsnCd" id="idSelectRsnCd" style="height:25px; width:200px">
    <form:option value="" label="--- Select Reason ---"/>
    <form:options items="${RSN_LIST}" itemValue="rtrnRsnCd" itemLabel="rtrnRsnNm"/>
</form:select>

Step 3.3. The second select box is re-constructed (ID:idSelectRsnCd)
dynamic-combo2