Find selected item in Datalist in HTML

2019-01-15 09:56发布

I've 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'm adding "option" using jquery to datalist. Now the question is how can i find which option is selected/clicked by the user in datalist. I want to get the id of option as soon as it is is selected/clicked by user?

4条回答
一夜七次
2楼-- · 2019-01-15 10:28

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'));
    });
});

http://jsfiddle.net/smap06ro/45/

查看更多
ら.Afraid
3楼-- · 2019-01-15 10:30

Try this, I got the '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
查看更多
劫难
4楼-- · 2019-01-15 10:45

You can add an ID to the input field - and listen for the input event. Then you have to get the value of the input to use in the selector to get the selected option

$(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>

查看更多
劳资没心,怎么记你
5楼-- · 2019-01-15 10:45

You can check that with is(':selected')

$('#browsers option').each(function() {
    if($(this).is(':selected')){
     // Your code here with the selected value
   }
});

Or to get the selected option value

 $('#browsers').val();
查看更多
登录 后发表回答