-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
132 lines (119 loc) · 2.89 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
'use strict';
// Import stylesheets
import './style.css';
import types from './entity_types';
var fields = {
_inputs: {},
get defined() {
return Object.keys(this._inputs)
.filter(
function (k) {
return this._inputs[k];
}.bind(this)
)
.map(
function (k) {
return this._inputs[k];
}.bind(this)
);
},
set defined(_inputs) {
this._inputs = _inputs;
},
find: function (k) {
return this._inputs[k];
},
};
load(); // Simulates a window onload event
function load() {
fields.defined = {
name: document.querySelector('#name'),
type: document.querySelector('#type'),
registryNumber: document.querySelector('#registryNumber'),
};
init();
}
function init() {
try {
const orgNameInput = fields.find('name');
if (!orgNameInput) return;
$(orgNameInput).autocomplete({
source: function (request, response) {
$.ajax({
url: 'https://orgbook.gov.bc.ca/api/v3/search/autocomplete',
data: {
q: request.term,
inactive: 'false',
revoked: 'false',
latest: 'true',
},
success: function (data) {
var results = data.total ? data.results : [];
response(results);
},
});
},
minLength: 2,
select: function (event, ui) {
clearFields();
getOrgData(ui.item);
},
});
} catch (e) {
console.error('Unable to initialize autocomplete', e);
}
}
function getOrgData(selected) {
$.ajax({
url: 'https://orgbook.gov.bc.ca/api/v4/search/topic',
data: {
q: selected.topic_source_id,
},
beforeSend: function () {
disableFields();
},
})
.done(function (response) {
var topic =
response.total &&
response.results.find(function (_topic) {
return _topic.source_id === selected.topic_source_id;
});
populateFields(topic);
})
.fail(function (e) {
console.error('Unable to get organization data', e);
})
.always(function () {
enableFields();
});
}
function populateFields(topic) {
if (!topic) return;
const orgTypeInput = fields.find('type');
const orgRegistryNumberInput = fields.find('registryNumber');
if (orgTypeInput) {
var orgTypeAttribute = topic.attributes.find(function (attribute) {
return attribute.type === 'entity_type';
});
orgTypeInput.value = types[orgTypeAttribute.value];
}
if (orgRegistryNumberInput) {
orgRegistryNumberInput.value = topic.source_id;
}
}
function clearFields() {
fields.defined.forEach(function (field) {
field.value = '';
});
}
function disableFields() {
fields.defined.forEach(function (field) {
field.setAttribute('disabled', 'true');
});
}
function enableFields() {
fields.defined.forEach(function (field) {
field.removeAttribute('disabled');
});
}