Jquery select2预填充数据问题

时间:2016-03-03 18:06:26

标签: jquery html jquery-select2 select2

我想在select2

中预填充数据

以下是服务器的响应

https://jsfiddle.net/j6tv52s6/

如何对选择进行预填充?

enter image description here

这是我的[小提琴] [2]

这是HTML

<input type="hidden" name='zipcode_covered' id='zipcodeCollection' value="">
<select class="js-data-example-ajax" style="width:100%" multiple="multiple" placeholder='Pincode'></select>

这是脚本:

function formatRepo(repo) {
  if (repo.loading) return repo.text;
  var markup = '<div class="clearfix">' +
               '<div clas="col-sm-10">' +
               '<div class="clearfix">' +
               '<div class="col-sm-6">' + repo.zipcode + '</div>' +
               '</div>'
  markup += '</div></div>';
  return markup;
}

function formatRepoSelection(repo) {
  var cur_val = $('#zipcodeCollection').val();
  if (cur_val) {
    $('#zipcodeCollection').val(cur_val + "," + repo.zipcode);
  } else {
    $('#zipcodeCollection').val(repo.zipcode);
  } 
  return repo.zipcode;
}

$(document).ready(function(){
  $(".js-data-example-ajax").select2({
    ajax: {
      url: "getZipList",
      type: "POST",
      contentType: "application/json; charset=utf-8",
      delay: 250,
      data: function(params) {
        return {
          q: params.term, // search term
          page: params.page
        };
      },
      processResults: function (data, page) {
        return {
          results: data.items
        };
      },
      cache: true
    },
    escapeMarkup: function(markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 1,
    templateResult: formatRepo, // omitted for brevity, see the source of this page
    templateSelection: formatRepoSelection // omitted for brevity, see the source of this page  
  });
});

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题是正确的..你想用服务器中的选项填充选择下拉列表吗?

以下是如何使用ajax:

 $.ajax({
        type: "POST",
        url: ajaxUrl,
        dataType: "json",
        success: function (domain) {
            $.each(domain.ZipCodes, function (index, value) {
                    $("#zipcodeDropdown").append(
                        $("<option></option>").text(value.zipCode).val(value.zipId)
                    );
            });
        },
        error: function (event) {
            ShowErrorLabel("ERROR in ajax call(" + ajaxUrl + "): \n" + "Error : " + event.status + " - " + event.statusText);
        }
    });