Populate select box with ajax

Django -- Posted on Jan. 21, 2018

Populate select box with ajax

              
                function populateSelectBox($element,url,method,data,datatype,display_field){
  /*
  $element: a jquery element for example $('#myselectbox')
  url : the url link for ajax Call
  method: method post or get
  data: a dict {},
  datatype: xml or json,
  display_field : the field name for display in selectbox <option value="pk"> display_field </option>
  */
    $.ajax({
      url: url,
      method: method,
      data: data,
      datatype: datatype,
      success: function(response){
        var data = JSON.parse(response);
        $element.html('');
        if (data.length != 0) {
          d = '<option value selected="selected">---------</option>';
          for (var i=0 ; i < data.length ; i++ ) {
            d += '<option value="' + parseInt(data[i].pk) + '">' + data[i].fields[display_field] + '</option>';
          }
        } else {
          d = '<option value selected="selected">---------</option>';
        }
        $element.html(d);
      }
    });
}
                  
   
            

Related Posts