【问题标题】:Select2 4.0.3 unable to fill other select2 fields using ajax callSelect2 4.0.3 无法使用 ajax 调用填充其他 select2 字段
【发布时间】:2016-09-23 14:25:04
【问题描述】:

我对 Select2 有一些问题,基本上我需要使用从 Select2 Ajax 搜索中检索到的数据填充其他一些表单字段。

甚至在此处找到以下示例:

Select2 4.0 - Push new entry after creation

我无法使用从 Select2 中找到的结果以编程方式填充某些字段

例如,假设我有三个字段,我可以使用其中两个字段来搜索数据,并且我希望在选择 ajax 调用返回值之一后自动填充其他剩余字段。

所以,例如:

 Test field 01 (Select2 field)
 Test field 02 (Select2 field)
 Test field 03 (standard input field)

如果我在“测试字段 01”上搜索某些内容,我希望自动填充 02 和 03。

我已经实现了一种您可以在下面找到的解决方案,但不适用于 Select2 字段,仅适用于输入字段。

如果我使用代码检查器,我会看到“select”元素内的新选项已正确创建并标记为“selected”,但似乎“select2-selection__rendered”跨度元素在触发后未正确更新“改变”事件

在我的测试过程中,我还注意到,每次我从结果中选择一个值时,我用来更新数据的函数“updateselect2”被调用四次,因此我在结果中找到了 4 次相同的值目的地选择框。

查看下面的动画 gif 以了解完整的行为

我做错了什么?

我的设置是:

  • jquery-3.1.0
  • 选择2 4.0.3

您可以在下面找到我当前工作的完整示例:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
    <meta http-equiv="x-ua-compatible" content="ie=edge"/>
    <title>Test</title>
    <script src="jquery-3.1.0.min.js"></script>
    <link rel="stylesheet" href="select2.min.css"/>    
    <script src="select2.full.js"></script>


</head>
<body>
<div class="section ">
  <div class="container ">
    <div class="row">
        <div class="col-md-2">
          <div class="form-group">
            <label for="testField01" class="control-label">Test field 01</label>
            <select id="testField01" class="form-control" name="testField01" style="width:150px;">
              <option value=""></option>
            </select>
          </div>
        </div>
        <div class="col-md-2">
          <div class="form-group">
            <label for="testField02" class="control-label" >Test field 02</label>
            <select id="testField02" class="form-control" name="testField02" style="width:150px;">
              <option value=""></option>
            </select>
          </div>
        </div>
        <div class="col-md-4">
          <div class="form-group">
            <label for="testField03" class="control-label" style="width:150px;">Test field 03</label>
            <input id="testField03" class="form-control" value="" readonly="readonly" />
          </div>
        </div>
    </div>
  </div>
</div>

</body>

</html>

JAVASCRIPT:

var select2_query = {};

function markMatch(text, term) {
    // Find where the match is
    var match = text.toUpperCase().indexOf(term.toUpperCase());

    var $result = $('<span></span>');

    // If there is no match, move on
    if (match < 0) {
        return $result.text(text);
    }

    // Put in whatever text is before the match
    $result.text(text.substring(0, match));

    // Mark the match
    var $match = $('<span style="color:red"></span>');
    $match.text(text.substring(match, match + term.length));

    // Append the matching text
    $result.append($match);

    // Put in whatever is after the match
    $result.append(text.substring(match + term.length));

    return $result;
}

function updateselect2(elId, values) {

  var $element = $('#' + elId); // the element that Select2 is initialized on
  if ($element.attr('id') == undefined) {
    return false;
  }
  $element.empty();
  var $option = $("<option selected></option>"); // the new base option
  $option.val(values[elId]); // set the id
  $option.text(values[elId]); // set the text
  $element.append($option); // add it to the list of selections
  $element.trigger("change"); // tell Select2 to update
}


function formatResult(result) {
  if (result.loading) {
    return result.text;
  }
  var term = select2_query.term || '';
  var $formattedResult = markMatch(result.testField01 + ' - ' + result.testField03, term);

  return $formattedResult;
}

function formatSelection(selection) {
  if (!selection.selected) {
    updateselect2('testField02', selection);
    $('#testField03').val(selection.testField03);
  }
  return selection.testField01;
}


function initSearch(fieldId, searchType) {
    $("#" + fieldId).select2({
        ajax: {
            url: "/search/data",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    id: params.term, // search term
                    by: searchType,
                    page: params.page
                };
            },
            processResults: function (data, params) {
             params.page = params.page || 1;
                return {
                    results: data.items,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) {
            return markup;
        },
        minimumInputLength: 4,
        templateResult: formatResult,
        templateSelection: formatSelection,
        language: {
            searching: function (params) {
                select2_query = params;
                return 'Searching…';
            }
        }
    });
}

$(document).ready(function() {

  $('testField01').select2();
  $('testField02').select2();

  initSearch('testField01', 'testField01');
  initSearch('testField02', 'testField02');

});

JSON 数据样本:

{"total_count":1,"incomplete_results":false,"items":[{"id":1,"testField01":"123456789","testField01":"987654321", "testField03":"ABCDEFGHIJK"}]}

【问题讨论】:

    标签: javascript jquery ajax select2


    【解决方案1】:

    好吧,当您将选项附加到选择字段时,您需要重新初始化 select2 元素,例如:

    $element.select2("destroy");

    而不是 updateselect2() 函数中的 $element.trigger("change");

    此外,更改 select2 中的值的正确方法不是通过触发 change 侦听器,而是通过调用 .select2('val', thevalue) 在您的情况下由于新选项而不起作用,但请记住这一点。

    另一个注意事项:不需要在document.ready中初始化select2,因为initSearch会为你做。

    最后一点:您的示例 json 错误,您通过 testField01 两次

    【讨论】:

    • .select2('val', thevalue) 在 select2 4.0.x 中已弃用,替换为 .val(thevalue)
    • 很好的提醒,没有注意到,因为我个人还在使用 3.5。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多