2016-12-27 7 views
0

Я хочу использовать плагин Select2 для загрузки удаленных данных и настройки поля выбора. Я следил за документацией, и это работало как шарм. Но когда пользователь не может найти его соответствие, появляется сообщение: «Результаты не найдены».Динамически отображается опция по умолчанию, когда «Не найдено результатов» в модуле Select2 jquery

Вместо этого сообщения мое требование является иметь параметр по умолчанию будет отображаться, если пользователь не может найти совпадение, подобное этому http://prntscr.com/dodf8k

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"><b>' + repo.full_name + '</b></div>' + 
    '</div>'; 

    if (repo.description) { 
     markup += '<div>' + repo.description + '</div>'; 
    } 

    markup += '</div></div>'; 

    return markup; 
    } 

    function formatRepoSelection (repo) { 
    return repo.full_name || repo.text; 
    } 

$(document).ready(function(){ 

    $(".js-data-example-ajax").select2({ 
     ajax: { 
     url: "https://api.github.com/search/repositories", 
     dataType: 'json', 
     delay: 250, 
     data: function (params) { 
      return { 
      q: params.term, // search term 
      page: params.page 
      }; 
     }, 
     processResults: 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 the remote JSON data 
      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 

    }); 
    }); 

Я сделал fiddle с выбор2 плагин для загрузки удаленных данных. Пожалуйста, скажите мне, как мне это сделать?

ответ

0

Вы должны относиться к делу вы mentiond в функции «processResults», как это (fiddle):

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"><b>' + repo.full_name + '</b></div>' + 
 
    '</div>'; 
 

 
    if (repo.description) { 
 
     markup += '<div>' + repo.description + '</div>'; 
 
    } 
 

 
    markup += '</div></div>'; 
 

 
    return markup; 
 
    } 
 

 
    function formatRepoSelection (repo) { 
 
    return repo.full_name || repo.text; 
 
    } 
 

 
$(document).ready(function(){ 
 

 
    $(".js-data-example-ajax").select2({ 
 
     ajax: { 
 
     url: "https://api.github.com/search/repositories", 
 
     dataType: 'json', 
 
     delay: 250, 
 
     data: function (params) { 
 
      return { 
 
      q: params.term, // search term 
 
      page: params.page 
 
      }; 
 
     }, 
 
     processResults: 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 the remote JSON data 
 
      if(data.items.length > 0) { 
 
      \t console.log(data.items); 
 
      return { 
 
       results: data.items 
 
      }; 
 
      } 
 
      else return {results: [{ 'loading' : false, 'description' : 'others', 'name' : 'others', 'text' : 'others', 'full_name' : 'Some Name' }]} 
 
     }, 
 
     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 
 
     
 
    }); 
 
    });
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/> 
 
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script> 
 
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script> 
 

 

 

 
<select class="js-data-example-ajax" style="width:100%"> 
 
    <option value="3620194" selected="selected">Select a value......</option> 
 
    <option>others</option> 
 
</select>

+0

Другие опции появляется, когда нет результатов, но почему это не выбираемые? Мне нужно сделать его доступным для пользователя, чтобы я мог получить значение на бэкэнд. –

 Смежные вопросы

  • Нет связанных вопросов^_^