0

select2にデータを事前入力したい

これがサーバーからの応答です

https://jsfiddle.net/j6tv52s6/

select への事前入力を行うにはどうすればよいですか?

ここに画像の説明を入力

これが私の[フィドル][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  
  });
});
4

1 に答える 1

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);
        }
    });
于 2016-03-03T18:13:04.690 に答える