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

标签 javascript forms conditional-statements dropdown

我正在创建在线表单,在表单中,我有一个文本(数字)字段和一个包含多个选项的下拉列表。当文本字段的值低于零时,我需要显示其中一些选项,当文本字段的值大于 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,您可以使用 templatedata-* 一起使用,并通过根据输入值测试 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>

关于javascript - 根据文本字段值显示\隐藏选择字段选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56430379/

相关文章:

javascript - 如何屏蔽字符串中的字母和数字

c# - 无法加载 MicrosoftAjax.debug.js

javascript - 绝对路径不适用于使用 typescript 创建 react 应用程序

javascript - jQuery 验证插件提交有问题吗?

r - 结合基于多个条件的观察

html - CSS 中的条件样式

javascript - 对本地文件系统的 AJAX 请求在 Chrome 中不起作用?

javascript - 使用特定按钮提交表单

ruby-on-rails - 使用条件 Rails 按计数范围排序

jquery 使用数组序列化输入