2016-09-23 2 views
4

나는 select2 드롭 다운 플러그인으로 작업 중입니다. 자동 메일에 기존 메일 ID가있는 select2 필드를 추가해야하는 상황이 발생했습니다. 그렇게 할 수 있었지만 같은 필드에있는 앱에없는 새 메일 ID를 추가해야합니다. 나는 그것을 해결할 수 없다. 아무도 나를 도와주세요.select2 드롭 다운 플러그인이 새 레코드 추가와 함께 자동으로 채워집니다.

여기 내보기 페이지 코드입니다.

<input type="hidden" class="select2 to_email w-100" name="to_email[]" 
data-role="to_email" data-width="100%" data-placeholder="To" value=""> 

JS 코드 : 내가 아는

$('body').on('click','[data-button="reply-mail"],[data-click="reply"]', function() { 
    attach = []; 
    var $ti = $(this).closest('[data-role="row-list"]').find('[data-role="reply-mail-wrap"]'); 
    var $to_this = $ti.find('[data-role="to_email"]'); 
    var mail_toadr = $ti.find('input[name="to_addr"]').val(); 
    $($to_this).select2({ 
     placeholder: "Search for a contact", 
     minimumInputLength: 3, 
     //maximumSelectionLength: 1, 
     multiple : true, 
     ajax: { 
      url: Utils.siteUrl()+'mailbox/get_all_contacts', 
      type: 'POST', 
      dataType: 'json', 
      quietMillis: 250, 
      data: function (term, page) { 
       return { 
        term: term, //search term 
        page_limit: 100 // page size 
       }; 
      }, 
      results: function (data, page) { 
       return { results: data}; 
      } 

     }, 
     initSelection: function(element, callback) { 
      return $.getJSON(Utils.siteUrl()+'mailbox/get_all_contacts?email=' + (mail_toadr), null, function(data) { 
        return callback(data); 

      }); 
     } 
    }); 
}); 

는, 예를 작업하는 당신에게 더 좋을 수 있지만, 미안 해요, 내가 그것을 할 방법을 모르겠어요. 작은 도움을 스크린 샷 :

http://awesomescreenshot.com/08264xy485이 친절하게 도와 ..

답변

1

은 내 요구 사항에 대한 수정을 가지고있다. 필드에 존재하지 않는 값을 입력하면 결과 : function (data, page) {...}은 빈 배열을 반환합니다. 우리로 이것을 확인할 수 있습니다

results: function (data, page) { 
    for (var obj in data) { 
     id = JSON.stringify(data[obj].id); 
     text = JSON.stringify(data[obj].text); 
     if (id == '"0"') { 
      $ti.find('.to_email').select2('val', '<li class="select2-search-choice"><div>'+ text +'</div><a tabindex="-1" class="select2-search-choice-close" onclick="return false;" href="#"></a></li>'); 
     } 
    } 
    return { results: data}; 
} 

그러나이보다 더 나은 우리가 (여기서는 Utils.siteUrl()+'mailbox/get_all_contacts'를) 결과를 가져올 위치를이 지역에 체크를 수행하는 것이 좋습니다. JS에서

function get_all_contacts() 
{ 
    // $contacts is the result array from DB. 
    // $term is the text to search, eg: 111 

    foreach($contacts as $contact_row) { 
     $contact_all[] = array('id' => $contact_row['id'], 'text' => $contact_row['primary_email']); 
    } 
    if (empty($contact_all)) { 
     $contact_all = array('0' => array('id' => 'undefinedMAILID_'. $term, 'text' => $term)); 
    } 
    $contact_data['results'] = $contact_all; 
    send_json_response($contact_all); 
} 

얻기 값 : 나는 내 문제를 해결하기 위해 이런 짓을했는지이 사람을 도움이 될 것입니다

sel_ids = $('.to_email').select2('val'); 
console.log(sel_ids); 

// console will show - ["value if mail id is existing", "undefinedMAILID_111"] 

희망을.