I want to create an event that fires on a change, so I can create something like a <select>
tag, but my code is not working with a <datalist>
.
This is my HTML:
<input type="text" name="team" id="favorite_team" list="team_list">
<datalist id="team_list">
<option>Detroit Lions</option>
<option>Detroit Pistons</option>
<option>Detroit Red Wings</option>
<option>Detroit Tigers</option>
</datalist>
And this is my JQuery code:
$('#favorite_team').on('change', function(){
alert($(this).val());
});
I want to create an event that fires on a change, so I can create something like a <select>
tag, but my code is not working with a <datalist>
.
This is my HTML:
<input type="text" name="team" id="favorite_team" list="team_list">
<datalist id="team_list">
<option>Detroit Lions</option>
<option>Detroit Pistons</option>
<option>Detroit Red Wings</option>
<option>Detroit Tigers</option>
</datalist>
And this is my JQuery code:
$('#favorite_team').on('change', function(){
alert($(this).val());
});
Share
Improve this question
edited Mar 17, 2015 at 13:15
asked Mar 17, 2015 at 12:29
user2166164user2166164
2 Answers
Reset to default 3Your selector is wrong, change the id of your input to favorite
or try this code:
$('#favorite_team').on('input', function(){
alert($(this).val());
});
You can add the loop to judge the option which is in the list.
$('#favorite_team').on('input', function(){
var options = $('datalist')[0].options;
for (var i=0;i<options.length;i++){
if (options[i].value == $(this).val())
{alert($(this).val());break;}
}
});
JSFiddle