I want to have select element so that my users can choose from a list of items, or if they like, type a new value that doesn't exist.
I know I can do a select like:
<select name="myDropdown" id="myDropdown">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
But you can't type into this select. So the next option I found is to use a dataset like:
<input type="text" list="existing-list" id='free-hand-enabled-dropdown'/>
<datalist id="existing-list">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</datalist>
This is much closer, but the text attribute for the option does not display when chosen, only the value is displayed. As a matter of fact, when you inspect this element, the text has been wiped on page load. And the value and text appear together in the dropdown list.
I can see how this would work if you just wanted to suggest some items to save the user from typing.
I just want a select element that allows the user to pick from the list as usual, or, type into the input box instead. When the submit button is pressed, javascript will submit the text and value attributes. If the value attribute is blank, I will know that it is a new entry. Open to suggestions if this is an awful idea!
Here is the jquery solution.
I replaced the text to title attribute, because custom attribute would easily to get.
function submit(){
const input = $("#free-hand-enabled-dropdown").val();
//check if the attribute value and label exist
if(typeof $("#existing-list option[value='" + input + "']").attr("value") &&
typeof $("#existing-list option[value='" + input + "']").attr("label") == 'undefined'){
console.log(input);
}else{
console.log($("#existing-list option[value='" + input + "']").attr("value"),$("#existing-list option[value='" + input + "']").attr("label"));
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" list="existing-list" id='free-hand-enabled-dropdown'/>
<datalist id="existing-list">
<option value="1" label="One"></option>
<option value="2" label="Two"></option>
<option value="3" label="Three"></option>
</datalist>
<button type="button" onclick="submit()">Submit</button>