在select2中获取当前输入

时间:2015-06-24 09:20:17

标签: jquery jquery-select2

我在多个输入上初始化select2。但是在进行AJAX调用以获取项目时,我需要传递一个附加参数,该参数存储在我应用select2的每个输入的data-id属性中。所以我需要获得对当前输入的引用。

以下是一个例子:

<input class="event-period" data-id="1"/>
<input class="event-period" data-id="2"/>

<script type="text/javascript">
$('.event-period').select2({
    ajax: {
        url: "/some-url/",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            // need to get data-id of current input here
            // the "this" keyword is the ajax object, so I can't use that
            return {
                query: params.term,
                page: params.page
            };
        },
        processResults: function (data, page) {
            return {
                results: data.items
            };
        }
    }
});
</script>

1 个答案:

答案 0 :(得分:2)

使用&#34;每个()&#34;定义输入时的JQuery函数

   $('.event-period').each(function(){
      var id = $(this).attr("data-id");
      $(this).select2({
        ajax: {
            url: "/some-url/",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                alert(id); //<-  now you can get this
                // need to get data-id of current input here
                // the "this" keyword is the ajax object, so I can't use that
                return {
                    query: params.term,
                    page: params.page
                };
            },
            processResults: function (data, page) {
                return {
                    results: data.items
                };
            }
        }
      });
    });