2013-01-14 21 views
8

我使用的是AJAX的選擇二(下面的代碼)插入後:在選擇二組數據與AJAX

$(".select2-ajax").select2({ 
     placeholder: "Search user", 
     minimumInputLength: 1, 
     ajax: { 
      url: $('#url-search-client').val(), 
      dataType: 'json', 
      type: 'post', 
      data: function (term, page) { 
      return { 
       filter: term 
      }; 
      }, 
      results: function (data, page) { 
      return {results: data}; 
      } 
     }, 
     width : '50%', 
     formatInputTooShort: function() {return 'Informe mais caracteres'; }, 
     formatResult: formatResultSelectAjax, // omitted for brevity, see the source of this page 
     formatSelection: formatSelectAjaxValue, // omitted for brevity, see the source of this page 
     dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller 
    }); 

好了,如果沒有找到客戶端,用戶可以使用一個按鈕來打開一個模式並添加新的客戶端,可能使用新客戶端的返回(帶有id和namae的json),並將數據(如名稱)放入select2中作爲選定項?

$('.btn-form-client').click(function() { 
     $.ajax({ 
      url: $('#frm-client').attr('action'), 
      dataType: 'json', 
      type: 'post', 
      data: $('#frm-client').serialize() 
     }).done(function (data) { 
      $('#modal-client').modal('hide') 
     }); 
     return false; 
    }); 
+0

你能做這個工作嗎? – Sebastialonso

回答

1

我設法使它工作。 POST jQuery中後,我得到了新的數據的JSON,並設置隱藏的輸入和選擇(「.select2-阿賈克斯)

$('#client=id').val(data.id); 
$('#modal-solicitante').modal('hide'); //This is my 
$(".select2-ajax").select2('data', {id: data.id, name: data.name, email: data.email}); 
18

開始在v4.x中,選擇2不再使用隱藏input場。相反,你create a new Option並追加到select元素:

var newOption = new Option(data.name, data.id, true, true); 
$(".select2-ajax").append(newOption).trigger('change'); 

true參數的組合和trigger('change')將確保你的新<option>被添加之後,自動選擇。

查看我的codepen以獲得完整的工作示例。

+0

一個聰明的方式來添加一個選項。之前沒有意識到這個對象。 – Ananda

+0

如果你想添加一個帶有空格的選項,需要修正jquery查找以用單引號括住選項值: 'if($(「#state」)。find(「option [value ='」+ newStateVal +「']」)。length){' – Mark

+0

謝謝,我已經更新了我的codepen。 – alexw