Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the change event for a datalist?

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.

like image 380
user_78361084 Avatar asked May 14 '14 06:05

user_78361084


People also ask

How do I use Onchange in a Datalist?

Replace the datalist by select tag. Or if you want to use <datalist> you can use event onchange on the <input> tag and check if the value of your input is into the values of datalist.

Can Datalist be styled?

Like select elements, the datalist element has very little flexibility in styling. You cannot style any of the suggested terms if that's what your question was asking. Browsers define their own styles for these elements.

Is the Datalist tag and select tag same?

Generally, both the tags are used for choosing an option from the given list. But the main difference between both is that in the <datalist> tag the user can enter its own input and add that as an option with the help of the <input> element whereas the <select> tag doesn't provide this feature.

How is the Datalist element used?

The <datalist> tag is used to provide an "autocomplete" feature for <input> elements. Users will see a drop-down list of pre-defined options as they input data.


1 Answers

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

$(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) {
          alert(val);
          break;
       }
    }
});

FIDDLE

like image 107
deadulya Avatar answered Sep 21 '22 13:09

deadulya