2014-02-18 75 views
1

我正在为我的项目使用Jquery Select2。我想在加载页面时在单个输入字段中保留默认值。我试图通过设置initSelection而我开始这样的select2组件。select2单个字段的默认值

$(document).ready(function() { 
     allowClear: true, 
     ajax: { // instead of writing the function to execute the request we use Select2's convenient helper 
      dataType: 'json', 
      url: "public/data.php", 
      data: function (term, page) { 
       return { 
        q: term, // search term 
        component: "map", 
        all_selected: $("#map-all").hasClass("active"), 
        parent_value: $("#city").val(), 
        child_value: "" 
       }; 
      }, 
      results: function (data, page) { // parse the results into the format expected by Select2. 
       // since we are using custom formatting functions we do not need to alter remote JSON data 
       return {results: data}; 
      } 
     }, 
     initSelection: function(element, callback) { 
      return $.getJSON("public/data.php?q="+element.val()+"&component=map&all_selected=false&parent_value=&child_value=", null, function(data) { 
       if ($.isFunction(callback)) { 
       return callback(data); 
       } 
      }); 
     }, 
     formatSelection: format, 
     formatResult: format, 
}); 

但是,这不起作用,因为它应该是。

但是,当我将multiple: true,设置为select2选项时,此功能完美无缺。我如何为单隐藏领域做到这一点?

谢谢&关心!

回答

1

好吧,我通过将回调从return callback(data);更改为return callback(data[0]);来解决此问题。我认为这背后的原因是因为该字段不是多字段,它只接受一个对象到回调函数。