How to use and build a datalist with validation in Bootstrap Studio
- Add an input type text to your form
- Set the needed attributes
data-countries
list=“countries” important that the list has the same value as the data-
placeholder=“Select a Country”
required
autocomplete=“off”
when you are done it should look something like this
html mark up
<input class="form-control"
type="text"
data-countries="England, Germany, China"
list="countries"
name="favCountry"
placeholder="Select a Country"
required
autocomplete="off"
/>
- Because we need to make the validation with javascript
we can build the datalist as well, no need for custom code
add this to a javascript file
Javascript
document.addEventListener('DOMContentLoaded', function () {
const inputs = document.querySelectorAll('input[list]');
inputs.forEach((input) => {
const dataListId = input.getAttribute('list');
const dataOptions = input.dataset[dataListId];
const options = dataOptions.split(',').map((option) => option.trim());
const datalist = document.createElement('datalist');
datalist.id = dataListId;
options.forEach((option) => {
const optionElement = document.createElement('option');
optionElement.value = option;
optionElement.text = option;
datalist.appendChild(optionElement);
});
input.parentNode.appendChild(datalist);
});
inputs.forEach((input) => {
input.addEventListener('change', function () {
let optionFound = false,
datalist = this.list;
const optionsArray = Array.from(datalist.options);
optionFound = optionsArray.some((option) => option.value === this.value);
if (optionFound) {
this.setCustomValidity('');
} else {
this.setCustomValidity('Please select a valid value.');
}
});
});
});
here is an example