Reputation: 23650
I need to load a large JSON file in to become the menu options for a selectize.js input field. In my working example below the AJAX call is not made until the users first types something into the box. Grateful for assistance to get the JSON file to load at the start with the page.
countries.json
[{"name":""}, {"name":"Afghanistan"}, {"name":"Belgium"}, {"name":"China"},{"name":"Denmark"}, {"name":"Estonia"}, {"name":"Finland"}, {"name":"Greece"}]
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>selectize</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.4/css/selectize.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.4/js/standalone/selectize.js"></script>
</head>
<body>
<label for="countries">Selectize</label>
<select class="form-control pickerSelectClass" id="countries"></select>
<script>
$('#countries').selectize({
valueField: 'name',
valueField: 'name',
labelField: 'name',
maxItems: 3,
options: [],
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'countries.json',
type: 'GET',
dataType: 'json',
data: { country: query, },
error: function() { callback(); },
success: function(res) { callback(res); }
});
}
});
</script>
</body>
</html>
Upvotes: 1
Views: 3909
Reputation: 23650
A kindly soul in an IRC channel has pointed me towards this solution, which seems to work nicely:
$.ajax({
url: 'countries.json',
type: 'GET',
dataType: 'json',
data: { json: JSON.stringify(countries) },
error: function(err) { console.log(err); },
success: function(options) {
$('#countries').selectize({
valueField: 'name',
labelField: 'name',
searchField: 'name',
maxItems: 3,
preload: true,
options: options,
create: true,
});
}
});
Upvotes: 2