我想制作一些跟踪数据列表中未过滤选项数量的代码。那么我怎么能跟踪这个呢?
其次,如果列表中只剩下一个选项,我想访问此选项的值。
以下是w3c规范的链接:https://www.w3.org/TR/html5/forms.html#the-datalist-element
注意:我想使用datalist,所以我不想在datalist上创建自己的过滤器并从那里获取值。
到目前为止我想出了这个代码:
小提琴:https://jsfiddle.net/6usf7j9g/
HTML
<h3>Anything you'd like?</h3>
<input id="your-favourite" list="choices"/>
<datalist id="choices">
<option value="Laphroaig"></option>
<option value="Jameson"></option>
<option value="Talisker"></option>
<option value="Oban"></option>
<option value="Dalwhinnie"></option>
<option value="Glennfidich"></option>
<option value="Glenlivet"></option>
</datalist>
的jQuery / JS
var selectedChoices = null; //in this variable I need to know how many items are left in the list after filtering. If you type "Glen" it should be two, if you type "Glenn", "J", etc. it should give a value of 1. It only needs to work on google chrome.
$("#your-favourite").on("keyup", function(){
selectedChoices = null; //PART OF THE ISSUE: Should change the value of the variable here, depending on the options that are showing.
if(selectedChoices === 1){
let finalOption = "unknown"; //PART OF THE ISSUE: Should load the value of the remaining option
// validate success
alert("There is only one value left in the list! It is called: " + finalOption);
selectedChoices = null; // reset value to 0.
}
// log the datalist and input elements, it might have some info that helps finding a solution.
console.log($("#your-favourite"));
console.log($("#choices"));
}); // end on keyup