问题
I have found plenty of other questions, but all of their answers have been unable to resolve my issue.
I am trying to set the value of a selectize.js input to a specified value.
Here is what I am doing:
$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);
});
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.
回答1:
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>
来源:https://stackoverflow.com/questions/51516582/selectize-additemvalue-adds-the-value-of-the-item-and-not-the-items-label