Dimitris Kougioumtzis Blog About technology

Populate select box with ajax

Category Django

Posted on Jan. 21, 2018



Populate select box with ajax


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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);
      }
    });
}

About

My name is Dimitris Kougioumtzis and i work as a Web developer at Rapidbounce Company

Elsewhere