<input id="test" type="text" list="list">
<datalist id="list">
<option value="A">First option</option>
<option value="B">Second option</option>
</datalist>
$("input").keyup(function(event) {
//any event like this for example...
console.log(event.target.value);
});
我不希望在用户单击某个选项后触发此事件。尽管不太可能工作(javascript),但已经尝试了以下操作:
$("option").click(function(e) {
e.preventDefault();
e.stopPropagation();
});
既然我使用的是
keyup
事件而不是input
,为什么要触发事件?... 最佳答案
使用Keypress
执行。
更新
您需要从事件中调用值而不是onload
$("input").keypress(function(event) {
//any event like this for example...
console.log("Hello from the other side");
});
$('#test').change(function(){ // you need to call the value from the event inside not a onload
console.log(document.getElementById("test").value) //no need
console.log($(this).val()) // jquery alredy present so simple use that
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test" type="text" list="list">
<datalist id="list">
<option value="A">First option</option>
<option value="B">Second option</option>
</datalist>