select2获取所选选项的值

时间:2018-02-28 06:04:05

标签: jquery jquery-select2



<select id="category" class="form-control select2-hidden-accessible" name="category" style="width: 100%;" tabindex="-1" aria-hidden="true">
          <option value="1">ICT</option>
</select>
&#13;
&#13;
&#13;

我想在select2中添加选项时输出上面的输出。我将select2初始化为:

&#13;
&#13;
var site_url = '<?php echo site_url(); ?>';
var URL = site_url + "Autocomplete_Control/autocomplete_category";
$('#myModal select').css('width', '100%');
$('#category').select2({
  tags: false,
  multiple: false,
  minimumInputLength: 3,
  minimumResultsForSearch: 10,
  ajax: {
    url: URL,
    dataType: "json",
    type: "GET",
    data: function(params) {
      var queryParameters = {
        term: params.term
      };
      return queryParameters;
    },
    processResults: function(data) {
      return {
        results: $.map(data, function(item) {
          return {
            text: item.category_name,
            id: item.sys_id
          };
        })
      };
    }
  }
});
&#13;
&#13;
&#13;

我想在选择1时从该选项中获取值ICT

我得到的方式是:

&#13;
&#13;
$('#category').on("select2:selecting", function(e) {
  // what you would like to happen
  var category_id = $(this).select2().find(":selected").val();
  console.log(e.target)
  console.log(category_id)
  console.log($("option:selected", e.currentTarget).val())

  console.log($('#category').select2('data'));
  particular(id); //i want to send the ID for another select2
});
&#13;
&#13;
&#13;

以上所有内容都会返回undefined

如何获取值1

我想获得值1,因为我将在另一个select2中使用它作为参数。在那里,我将选择具有category_id 1的所有特定内容。假设value=1是select2初始化的id:sys_id

1 个答案:

答案 0 :(得分:0)

$('#category').on("change", function(e) {
  // what you would like to happen
  var category_id = $(this).select2().find(":selected").val();
  console.log(category_id)
});

我使用了常规change事件,并返回正确的$(this).select2().find(":selected").val();