JavaScript API Examples

Examples of how to interact with the control programmatically.

var control = new TomSelect('#select-tools',{
	maxItems: null,
	valueField: 'id',
	labelField: 'title',
	searchField: 'title',
	options: [
		{id: 1, title: 'Spectrometer', url: 'http://en.wikipedia.org/wiki/Spectrometers'},
		{id: 2, title: 'Star Chart', url: 'http://en.wikipedia.org/wiki/Star_chart'},
		{id: 3, title: 'Electrical Tape', url: 'http://en.wikipedia.org/wiki/Electrical_tape'}
	],
	create: false
});

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

document.getElementById('button-clear').addEventListener('click', function() {
	control.clear();
});

document.getElementById('button-clearoptions').addEventListener('click', function() {
	control.clearOptions();
});

document.getElementById('button-addoption').addEventListener('click', function() {
	control.addOption({
		id: 4,
		title: 'Something New',
		url: 'http://google.com'
	});
});

document.getElementById('button-additem').addEventListener('click', function() {
	control.addItem(2);
});

document.getElementById('button-setvalue').addEventListener('click', function() {
	control.setValue([2, 3]);
});
<select id="select-tools" multiple placeholder="Pick a tool..."></select>
<div class="buttons pt-3">
	<input type="button" value="addItem()" id="button-additem">
	<input type="button" value="addOption()" id="button-addoption">
	<input type="button" value="setValue()" id="button-setvalue">
	<input type="button" value="clear()" id="button-clear">
	<input type="button" value="clearOptions()" id="button-clearoptions">
</div>