2 回答
TA贡献1829条经验 获得超9个赞
使用香草JavaScript,您可以用模板沿data-*和重建选择框通过测试,显示一定的值data-*与输入值的值。
const input = document.querySelector('#text')
const select = document.querySelector('#list')
const template = document.querySelector('template')
input.addEventListener('input', e => {
let val = parseInt(e.target.value)
// Clone the template
let t = document.importNode(template.content, true)
// Create a fragment for the new list
let f = document.createDocumentFragment()
for (var i = 0; i < t.children.length; i++) {
let child = t.children[i]
let show = parseInt(child.getAttribute('data-show') || '0')
// If the data-show is larger than zero and in the input is larger than zero
// Clone the current option and place it in the fragment
if(show > 0 && val > 0) f.appendChild(child.cloneNode(true))
// If the data-show is smaller than zero and in the input is smaller than zero
// Clone the current option and place it in the fragment
if(show < 0 && val < 0) f.appendChild(child.cloneNode(true))
}
// If the fragment doesn't have any options display a message
if (f.children.length == 0) {
let option = document.createElement('option')
option.textContent = 'Enter a number in the text field'
f.appendChild(option)
}
// Set the value of the select
select.innerHTML = ''
select.appendChild(f)
})
<form id="test" name="test" target="_self">
<input id="text" name="text field" type="text">
<select id="list" name="list" size="1">
<option>Enter a number in the text field</option>
</select>
</form>
<template>
<option data-show="-1" value="1">1</option>
<option data-show="-1" value="2">2</option>
<option data-show="1" value="3">3</option>
<option data-show="1" value="4">4</option>
<!-- This value should never show since it is set to zero -->
<option data-show="0" value="5">5</option>
<!-- This value should never show since it doesn't have a data-show attribute -->
<option value="6">6</option>
</template>
添加回答
举报