How to get data attribute of <select> for use in select2 from inside .select2() ajax call?

只谈情不闲聊 提交于 2019-12-11 10:43:22

问题


I need to know what element my select2 UI is based on so that I can grab data from a data-attribute. Maybe I'm missing it in the docs, but I can't seem to figure out how to get it.

Here is the basics of how my code is set up:

<form>
  <!--SNIP-->
  <select class="select-records" data-index=0>
    <option>Choose some records</option>
  </select>
  <!--SNIP-->
</form>

<script>
  $('.select-records').select2({
    ajax: {
      url: "/ajax/records",
      dataType: 'json',
      delay: 250,
      data: function (params) {
        // Need to get the data-index of the base <select> to process/pass along more info here
        return {
          q: params.term,
          page: params.page
        }
      },
      processResults: function(data, page) {
        return {
          results: data.items
        }
      },
      cache: true
    },
    minimumInputLength: 3
  });
</script>

As you can see, I need to access the data attribute (or id) inside the function that defines the params to sent with the ajax request.


回答1:


Let's say that you want to add to your ajax query ...&ui=select1 for your select element.

  1. Define your select in the following way: <select data-ajax--id='select1' class="select-records" data-index=0>

  2. Your ajax's data function should now be:

    function (params) { return { q: params.term, ui: this.id, page: params.page } }



来源:https://stackoverflow.com/questions/32259070/how-to-get-data-attribute-of-select-for-use-in-select2-from-inside-select2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!