【问题标题】:Show\hide select field options base on text field value根据文本字段值显示\隐藏选择字段选项
【发布时间】:2019-10-19 04:29:01
【问题描述】:
我正在创建在线表单,在表单中,我有一个文本(数字)字段和一个包含多个选项的下拉列表。当文本字段的值小于零时,我需要显示其中一些选项,而当文本字段的值大于 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>
【问题讨论】:
标签:
javascript
forms
conditional-statements
dropdown
【解决方案1】:
你可能想给你的选项ID,因为使用值作为标识符可能会出现问题。还建议使用侦听器来输入文本字段,这是一个示例,因为我给选项的 id 为“option1”:
$('#text').on('input', function(){
if($('#text').val() > 0){
$('#option1').show();
}
else($('#option1').hide());
})
【解决方案2】:
使用 vanilla javascript,您可以使用 template 和 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>