Find selected element in Datalist in HTML
I have a datalist something like this
<input list="browsers">
<datalist id="browsers">
<option id="op1" value="Internet Explorer">
<option id="op2" value="Firefox">
<option id="op3" value="Chrome">
<option id="op4" value="Opera">
<option id="op5" value="Safari">
</datalist>
I am adding "option" using jquery for datalist. Now the question is how can I find which option is selected / pressed by the user in the datalist. I want to get the id of an option as soon as it is selected / clicked by the user?
+3
source to share
4 answers
You can add an id to the input field - and listen to the input event. Then you have to get the value of the input to use in the selector to get the selected parameter
$(function() {
$('#browserinput').on('input',function() {
var opt = $('option[value="'+$(this).val()+'"]');
alert(opt.length ? opt.attr('id') : 'NO OPTION');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id='browserinput' list="browsers">
<datalist id="browsers">
<option id="op1" value="Internet Explorer" />
<option id="op2" value="Firefox" />
<option id="op3" value="Chrome" />
<option id="op4" value="Opera" />
<option id="op5" value="Safari" />
</datalist>
+7
source to share
Try this way
<input list="browsers" id="input">
<datalist id="browsers">
<option id="op1" value="Internet Explorer">
<option id="op2" value="Firefox">
<option id="op3" value="Chrome">
<option id="op4" value="Opera">
<option id="op5" value="Safari">
</datalist>
$(function(){
$('#input').change(function(){
console.log($("#browsers option[value='" + $('#input').val() + "']").attr('id'));
});
});
0
source to share
Try this, I got "data-id" value.
<input list="browsers" id="input">
<datalist id="browsers">
<option data-id="op1" value="Internet Explorer">
<option data-id="op2" value="Firefox">
<option data-id="op3" value="Chrome">
<option data-id="op4" value="Opera">
<option data-id="op5" value="Safari">
</datalist>
<script type="text/javascript">
$(function(){
$('#input').change(function(){
var abc = $("#browsers option[value='" + $('#input').val() + "']").attr('data-id');
alert(abc);
});
});
</script>
//if you click/choose 'Firefox' then 'op2' will show
0
source to share