Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  143] [ 2]  / answers: 1 / hits: 44207  / 10 Years ago, wed, may 14, 2014, 12:00:00

I am using a datalist and need to detect when the user selects something from the drop-down list. A similar question has been asked BUT I need it so that the event fires ONLY when the user selects something from the datalist. If they type something in the input then I do NOT want the event to fire. (Notice in the accepted answer to the question I linked that they bind the input, which is not what I want). I've tried (with no success):



<datalist>
<option>Option 1 Here</option>
<option>Option 2 Here</option>
</datalist>


$(document).on('change', 'datalist', function(){
alert('hi');
});


EDIT:
This question is different than the suggested question because it's a completely different question.


More From » jquery

 Answers
62

You can manually check it on change. But you need to check change of the input of datalist.


FIDDLE




$(document).on('change', 'input', function() {
var options = $('datalist')[0].options;
var val = $(this).val();
for (var i = 0; i < options.length; i++) {
if (options[i].value === val) {
console.log(val);
break;
}
}
});

<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js></script>

<input list=ff>
<datalist id=ff>
<option>Option 1 Here</option>
<option>Option 2 Here</option>
</datalist>




[#71024] Monday, May 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karyme

Total Points: 545
Total Questions: 102
Total Answers: 120

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
;