本文介绍了selectize.addItem(value)添加项目的值,而不是项目标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了很多其他问题,但是他们所有的答案都无法解决我的问题.

I have found plenty of other questions, but all of their answers have been unable to resolve my issue.

我正在尝试将selectize.js输入的值设置为指定值.

I am trying to set the value of a selectize.js input to a specified value.

这是我在做什么:

$select = $picker.selectize({
  valueField: 'id',
  labelField: 'displayName',
  searchField: 'displayName',
  options: [],
  create: false,
  // ... Omitted
});

if (initialValue.length > 0) {
  // Do a search for the user.
  jQuery.getJSON("/_api/GetUserById?Id=" + initialValue, function(data) {
    var results = data.value;
    if (results.length == 1) {
      $select[0].selectize.addOption(results[0]);
      $select[0].selectize.addItem(results[0].id);
    }
  }, function(err) {
    initialSearchForUserFailed(err);
  });

这确实可以成功更改输入的值,但是addItem方法将用户ID添加到selectize输入中,而不是其显示名称.

This does successfully change the value of the input, however, the addItem method adds the users Id to the selectize input instead of their display name.

推荐答案

可能是您的searchField值需要格式化为数组,但我无法重现您看到的显示问题.另外,从远程源返回数据的方式可能会出现问题.请参阅下面的工作示例,该示例可以帮助您进行故障排除:

Could be that your searchField value needs to be formatted as an array but I am unable to reproduce the display issue you are seeing. Also, could be an issue with how the data is being returned from your remote source. See the working example below that may help you troubleshoot:

// placeholder for data retrieved from remote source
const options = [
  {value: 1, text: 'Annie'},
  {value: 2, text: 'Bart'},
  {value: 3, text: 'Carol'}
];

// init selectize input
const field = $('#select1').selectize({
  options: [],
  placeholder: 'Select...',
  valueField: 'value',
  labelField: 'text',
  searchField: ['text'],
  create: false
});

// change the index to simulate retrieving a different option
let option = options[0];

// add first option to selectize input and select it
field[0].selectize.addOption(option);
field[0].selectize.addItem(option.value);
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Selectize</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.default.min.css">
  </head>

  <body>

    <form action="" method="POST">
      <input id="select1" name="select1" type="text" />
      <button type="submit">Submit</button>
    </form>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.js"></script>

  </body>

</html>

这篇关于selectize.addItem(value)添加项目的值,而不是项目标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:56