javascript - how to call change event like select on html datalist - Stack Overflow

I want to create an event that fires on a change, so I can create something like a <select> tag,

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
Add a ment  | 

2 Answers 2

Reset to default 3

Your 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745411875a4626570.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信