根据文本字段值显示\隐藏选择字段选项

我正在创建在线表单,在表单中,我有一个文本(数字)字段和一个包含多个选项的下拉列表。当文本字段的值低于零时,我需要显示其中一些选项,而当文本字段的值大于 0 时,我需要显示其他选项。


有人知道如何使用 JS 做到这一点吗?(后端没有数据库)。


谢谢你的帮助!


我只能使用 js (jquery) + css 来完成这项任务。


例子:


<form id="test" name="test" target="_self">

    <input id="text" name="text field" type="text">

    <select id="list" name="list" size="1">

        <option value="1">1</option>

        <option value="2">2</option>

        <option value="3">3</option>

        <option value="4">4</option>

    </select>

</form>


潇潇雨雨
浏览 128回答 2
2回答

PIPIONE

使用香草JavaScript,您可以用模板沿data-*和重建选择框通过测试,显示一定的值data-*与输入值的值。const input = document.querySelector('#text')const select = document.querySelector('#list')const template = document.querySelector('template')input.addEventListener('input', e => {&nbsp; let val = parseInt(e.target.value)&nbsp; // Clone the template&nbsp; let t = document.importNode(template.content, true)&nbsp; // Create a fragment for the new list&nbsp; let f = document.createDocumentFragment()&nbsp;&nbsp;&nbsp; for (var i = 0; i < t.children.length; i++) {&nbsp; &nbsp; let child = t.children[i]&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; let show = parseInt(child.getAttribute('data-show') || '0')&nbsp; &nbsp; // If the data-show is larger than zero and in the input is larger than zero&nbsp; &nbsp; // Clone the current option and place it in the fragment&nbsp; &nbsp; if(show > 0 && val > 0) f.appendChild(child.cloneNode(true))&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // If the data-show is smaller than zero and in the input is smaller than zero&nbsp; &nbsp; // Clone the current option and place it in the fragment&nbsp; &nbsp; if(show < 0 && val < 0) f.appendChild(child.cloneNode(true))&nbsp; }&nbsp;&nbsp;&nbsp; // If the fragment doesn't have any options display a message&nbsp; if (f.children.length == 0) {&nbsp; &nbsp; let option = document.createElement('option')&nbsp; &nbsp; option.textContent = 'Enter a number in the text field'&nbsp; &nbsp; f.appendChild(option)&nbsp; }&nbsp;&nbsp;&nbsp; // Set the value of the select&nbsp; select.innerHTML = ''&nbsp; select.appendChild(f)})<form id="test" name="test" target="_self">&nbsp; <input id="text" name="text field" type="text">&nbsp; <select id="list" name="list" size="1">&nbsp; &nbsp; <option>Enter a number in the text field</option>&nbsp; </select></form><template>&nbsp; <option data-show="-1" value="1">1</option>&nbsp; <option data-show="-1" value="2">2</option>&nbsp; <option data-show="1" value="3">3</option>&nbsp; <option data-show="1" value="4">4</option>&nbsp; <!-- This value should never show since it is set to zero -->&nbsp; <option data-show="0" value="5">5</option>&nbsp; <!-- This value should never show since it doesn't have a data-show attribute -->&nbsp; <option value="6">6</option></template>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript