I have a 2 part question relating to the <datalist> tag. Firstly - whilst this works in Chrome, is the following valid?
<datalist id="key1_list">
<option value="myval1">Disp 1</option>
<option value="myval2">Disp 2</option>
<option value="myval3">Disp 3</option>
</datalist>
And if it is, how does one get the selected display text from the <option> tag? In Chrome the value is the main text with the Disp 1 listed as small underneath. Does anyone know a way (in Jquery) to get the text() as there doesn't appear to be a selected flag listed on the selected option.
CodePudding user response:
Consider using input event. See example:
$(function() {
$("#myKey_list").on("input", function(event) {
var val = $(this).val();
console.log("Input: " val);
var opt = $("#key1_list option[value='" val "']");
console.log("Option: " opt.text());
$(this).val(opt.text());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="myKey_list">Choose from this list:</label>
<input list="key1_list" id="myKey_list" name="myBrowser" />
<datalist id="key1_list">
<option value="myval1">Disp 1</option>
<option value="myval2">Disp 2</option>
<option value="myval3">Disp 3</option>
</datalist>
As was mentioned by Perform action when clicking HTML5 datalist option
Due to the lack of events available for
<datalist>elements, there is no way to get a selection from the suggestions other than watching the input's events (change,input, etc).
When we identify a input we can then change the value based on the Option.
