2015-01-17 2 views
1

클래스를 사용하여 select2를 여러 개 사용하고 싶습니다. 예를 들어 자동 완성에서와 마찬가지로 select2에서 동일한 작업을 수행하지 못했습니다. 여기 select2에서 현재 요소 가져 오기

내 코드입니다 :

$('.select2-autocomplete').select2({ 
    placeholder: "Search", 
    minimumInputLength: 1, 
    multiple: true, 
    ajax: { 
    url: "http://example.com/autocomplete-results", 
    dataType: 'json', 
    data: function(term, page) { 
     return { 
     q: term, 
     type: $(this.element).data('type') 
     }; 
    }, 
    results: function(data, page) { 
     return { 
     results: data 
     }; 
    } 
    }, 
}); 

모든이를 제외하고 잘 작동 : 나는 선택 2 요소 데이터 유형 값이 필요하지만, 항상 어떤 생각을 정의되지 여기

type : $(this.element).data('type') 

어떻게 그걸 얻을 수 있니?

감사

편집 :

내가 아약스를 통해 데이터 형을 보내려는 이유는 그 아약스에서 다른 결과를 보여주고 싶은
<input type="hidden" data-type="products" name="products" class="select2-autocomplete"> 
<input type="hidden" data-type="customers" name="customers" class="select2-autocomplete"> 

+0

동적으로 데이터 유형을 설정해야하는 특별한 이유가 있습니까? – Craicerjack

+0

예 폼에 select2가 여러 개 있고 서버가 어떤 결과가 반환되는지 이해할 수 있어야합니다. 서버에 형식 매개 변수를 전달하고 싶습니다. – Mani

+0

데모가 도움이 될 것입니다. – Nima

답변

0

$(this.context)을 사용할 수 있으며 원본 선택 요소를 jQuery 개체로 반환합니다.

data: function(term, page) { 
    return { 
    q: term, 
    type: $(this.context).data('type') 
    }; 
}, 
2

당신은 그것을 활성을 캡처 할 수있는 요소를 select2 : open 이벤트 중에 누른 다음 데이터 함수로 사용하십시오.

여기 내 예제 :

(function(){ 
var theSelect2Element = null; 
$('.select2-autocomplete').select2({ 
    ... 
    data: function(term, page) { 
     return { 
     q: term, 
     type: $(theSelect2Element).data('type') 
     }; 
    }, 
    ... 
}).on('select2:open', function(e){ 
    theSelect2Element = e.currentTarget; 
}))(); 

행운을 빌어 요!