Eduard Luca
Eduard Luca

Reputation: 6612

Get current input in select2

I'm initializing select2 on multiple inputs. However when making the AJAX call to get the items, I need to pass an additional parameter, which is stored in the data-id attribute of each input which I'm applying select2 on. So I need to get a reference to the current input.

Here's an example:

<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>

Upvotes: 1

Views: 951

Answers (1)

Michael
Michael

Reputation: 435

use "each()" JQuery function when you define the inputs

   $('.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
                };
            }
        }
      });
    });

Upvotes: 2

Related Questions