Select with custom Input
Bootstrap Select with custom input - free examples & tutorial
Responsive Select with custom user input built with Bootstrap 5. Click on the Other option to input a custom value into the select.
To learn more read Select Docs.
Basic example
To make select with custom input option add to select style="display: inline;"
and right after select,
add disabled
input with style="display: none;"
. Also add a displayInput
class to the input div and label.
When we add display: none
to input it allows us to hide input when the user has not yet selected the "Other"
option in the select. Then, using the script given below, after selecting the "Other" option, we will
hide the select and remove display: none
and disabled
from the input.
In the input itself, we also have a function hideInput()
called onblur that checks if
there is any value in the input and if it is input is still visible.
In the absence of any value in the input, after clicking outside the input, it gets hidden and select is shown
<div id="textSelectdiv">
<select id="textSelect" data-mdb-select-init style="display: inline;">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="customOption">Other</option>
</select>
<label class="form-label select-label">Example label</label>
</div>
<div id="inputDiv" data-mdb-input-init class="form-outline disaplayInput">
<input type="text" id="form12" class="form-control" style="display: none;" onblur="hideInput()" disabled />
<label id="inputLabel" class="form-label disaplayInput" for="form12">Other</label>
</div>
.disaplayInput{
display: none;
}
const mySelect = document.getElementById("textSelect");
const inputOther = document.getElementById("form12");
const labelInput = document.getElementById("inputLabel");
const divInput = document.getElementById("inputDiv");
const selectDiv = document.getElementById("textSelectdiv");
mySelect.addEventListener('optionSelect.mdb.select', function(e){
const SelectValue = document.getElementById('textSelect').value;
if (SelectValue === 'customOption') {
inputOther.style.display='inline';
inputOther.removeAttribute('disabled');
labelInput.classList.remove('disaplayInput');
divInput.classList.remove('disaplayInput');
selectDiv.style.display='none';
inputOther.focus();
mySelect.disabled = 'true';
} else {
a.style.display='none';
}
})
function hideInput(){
if (inputOther !== null && inputOther.value === "")
{
inputOther.style.display='none';
inputOther.setAttribute('disabled', '');
selectDiv.style.display='inline';
mySelect.removeAttribute('disabled');
labelInput.classList.add('disaplayInput');
divInput.classList.add('disaplayInput');
}
}