如何获取select2中所选选项的data- *值?

时间:2016-11-02 15:31:41

标签: javascript jquery jquery-select2 select2 jquery-select2-4

这就像this topic的第二部分,现在我需要能够从一个选择到另一个选择读取动态data-*属性。这是什么意思?

首先看一下下图:

enter image description here

您所看到的是以下代码的作用:

// This turn 1st and 3rd into select2
$('#module, #conditions').select2();

// This turn 2nd into select2 using data from a datasource
$('select#fields').select2({
   placeholder: 'Select a field',
   data: data.fields
});

正如我在引用主题中发布的那样,data.fields有一个类似于以下内容的JSON:

"fields": [
  {
    "id": "companies_id",
    "text": "companies_id",
    "data-type": "int"
  },
  {
    "id": "parent_companies_id",
    "text": "parent_companies_id",
    "data-type": "int"
  },
  {
    "id": "client_of_companies_id",
    "text": "client_of_companies_id",
    "data-type": "int"
  },
  {
    "id": "asset_locations_id",
    "text": "asset_locations_id",
    "data-type": "int"
  },
  {
    "id": "companies_name",
    "text": "companies_name",
    "data-type": "varchar"
  },
  {
    "id": "companies_number",
    "text": "companies_number",
    "data-type": "varchar"
  }
]

在这种情况下,我需要从第3个选择(条件)上的data-*事件中读取分配给第2个选择(字段)的onChange()属性,然后对INPUT进行一些修改(但是这是在我身上。)

如何从任何其他select2元素中获取data-*值?

1 个答案:

答案 0 :(得分:1)

问题更多的是"如何在select2中获取所选选项的data-*值?"。

检查此示例:



var $example = $("#s1").select2({
  data: [
    {
      "id": "companies_id",
      "text": "companies_id",
      "data-type": "int",
      "data-extra": '1'
    },
    {
      "id": "parent_companies_id",
      "text": "parent_companies_id",
      "data-type": "int",
      "data-extra": '2'
    },
    {
      "id": "client_of_companies_id",
      "text": "client_of_companies_id",
      "data-type": "int",
      "data-extra": '3'
    },
    {
      "id": "asset_locations_id",
      "text": "asset_locations_id",
      "data-type": "int",
      "data-extra": '4'
    },
    {
      "id": "companies_name",
      "text": "companies_name",
      "data-type": "varchar",
      "data-extra": '5'
    },
    {
      "id": "companies_number",
      "text": "companies_number",
      "data-type": "varchar",
      "data-extra": '6'
    }
  ],
}).on('select2:select', function(e) {
  console.log(e.params.data['data-type'], e.params.data['data-extra']);
});
$('button').click(function() {
  option_el = $('#s1 :selected');
  data = option_el.data('data')
  
  console.log(data['data-type'])
  console.log(data['data-extra'])
});

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
<select id="s1">
</select>
<br />
<br />
<button>Click to the the `data-type` value</button>
&#13;
&#13;
&#13;