2014-02-18 1 views
1

내 프로젝트에 Jquery Select2을 사용하고 있습니다. 페이지가로드 될 때 단일 입력 필드에 기본값을 유지하려고합니다. 나는이 같은 select2 구성 요소를 시작하는 동안 initSelection 설정하여이 시도했다.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, 
}); 

그러나 이것은 정상적으로 작동하지 않습니다.

그러나 select2 옵션으로 multiple: true,을 만들면 완벽하게 작동합니다. 어떻게 하나의 숨겨진 필드에이 작업을 수행합니까?

감사합니다. & 감사합니다!

답변

1

그래, 콜백을 return callback(data);에서 return callback(data[0]);으로 변경하여이 문제를 해결했습니다. 그 이유는 필드가 여러 필드가 아니기 때문에 콜백 함수에 하나의 객체 만 허용하기 때문입니다.