我的代码中有一个很长的下拉列表(超过 3k+ 选项)。由于我的下拉列表太长,我决定使用数据列表,以便用户可以通过输入更轻松地过滤下拉列表。这样他们就不必滚动浏览所有 3k 选项。
我想让它让用户可以过滤它,但不能输入/使用不在下拉列表中的值。IE 输入值将是下拉列表中的一个选项或什么都没有。我不知道该怎么做。
例如,他们可以输入颜色 John,但是一旦他们离开输入,因为 John 不在下拉列表中并且他们没有从下拉列表中选择它,一旦他们点击提交,该值就会为空。但是,如果他们搜索蓝色并单击蓝色,则输入值仍将是蓝色,因为它位于数据列表下拉选项中。
提前致谢。
<form method = "POST">
<input class="form-control" type="text" id="color" list="colors_data" autocomplete = "off">
<datalist id="colors_data"style = "width:800px">
<option value="red"></option>
<option value="orange"></option>
<option value="green"></option>
<option value="blue"></option>
</datalist>
<input type = "submit" value = 'send_request'>
</form>
从选项值中获取所有颜色的数组,并检查是否包含您的输入值。
// Cache the elements
const options = document.querySelectorAll('option');
const form = document.querySelector('form');
const input = document.querySelector('#color');
const submit = document.querySelector('[type="submit"]');
// Add an click listener to the submit button
submit.addEventListener('click', handleSubmit, false);
// Iterate over the options with `map` and return a
// new array of colour values
const colors = Array.from(options).map(el => el.value);
function handleSubmit(e) {
// Prevent the form from submitting
e.preventDefault();
// Check to see if the input value is included
// in the colours array
if (colors.includes(input.value)) {
// If it is submit the form
console.log('Found');
// form.submit();
} else {
// Otherwise do nothing
console.log('Not found');
}
}
<input class="form-control" type="text" id="color" list="colors_data" autocomplete="off">
<datalist id="colors_data" style="width:800px">
<option value="red"></option>
<option value="orange"></option>
<option value="green"></option>
<option value="blue"></option>
</datalist>
<input type="submit" value='send_request'>
请注意,如果您不想写出所有 HTML,您可以使用数组以编程方式构建选项,并使用模板字符串创建标记。这样您就不必抓取单独的颜色数组进行检查,因为您已经有了一个。
const colors = ['red', 'orange', 'green', 'blue'];
// Iterate over the colour array to produce an array of strings
// that you then join into one string
function getOptions(arr) {
return arr.map(el => `<option value=${el}>${el}</option>`).join('');
}
// Grab the datalist element
const datalist = document.querySelector('datalist');
// And insert the options
datalist.insertAdjacentHTML('beforeend', getOptions(colors));
<datalist />
附加文件
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句