css 什么是最接近的解决方案,这个想法/问题,我有与表单的HTML?

0x6upsns  于 2023-01-03  发布在  其他
关注(0)|答案(3)|浏览(105)

我想创建一个HTML格式的选择表单,如果选中了第一个选择组中的某些选项,该表单将检查是否显示第二个选择组

<body>
    <form name="Test">
        <!-- all the factors to account for when calculating odds-->
        <div>
            <label>
            <select name="FirstList" id="FirstListID">
                <option value="1">First option</option>
                <option value="2">Second option</option>
                <option value="3">Third option</option>
            </select><br>
                
            <!-- SecondList would be visible if "1" is selected-->
            <label name="SecondList" style="display:none">List for "1":
                <select name="SecondListSelect" id="SecondListSelectID">
                    <option value="3">Placeholder</option>
                </select><br>
            </label>
            <!-- ThirdList would be visible if "2" is selected-->
            <label name="ThirdList" style="display:none">List for "2":
                <select name="ThirdListSelect" id="ThirdListSelectID">
                    <option value="4">Placeholder</option>
                </select><br>
            </label>
            <!-- No secondary select form appears if "3" is selected-->
        </div>
    </form>
</body>

我试过使用AddEventListeners,但是代码看起来不太好维护,因为我计划在主下拉菜单中添加更多的选项,所以我需要不断地根据选择的主选项添加出现的辅助选择组。我该如何在JS中编写代码呢?

k5ifujac

k5ifujac1#

为每个<label>指定一个标识符,将其绑定到应该可见的value。数据属性将起作用。然后,每当<select>发生变化时,迭代所有此类标签并隐藏它们。从select中取出.value,并使用字符串连接为数据集中的元素构造一个选择器,然后可以选择该元素并显示它。
例如,使用如下标签

<label data-option=1>

你本可以

for (const label of document.querySelectorAll('[data-option]')) {
  label.style.display = 'none';
}
document.querySelector(`[data-option=${select.value}]`).style.display = 'block';

在变更监听器中。

u91tlkcl

u91tlkcl2#

将第二个<select>元素的选项存储在一个对象中。确保键与第一个<select>中选项的value属性值匹配。
在第一个<select>上侦听change事件,每当发生更改时,清空第二个<select>的选项,从对象中获取新选项,并使用该数据创建新的<option>元素。
现在您有了一个易于扩展的动态<select>元素。

const optionData = {
  '1': [
    {
      label: 'Foo',
      value: 'foo',
    }
  ],
  '2': [
    {
      label: 'Bar',
      value: 'bar',
    },
    {
      label: 'Baz',
      value: 'baz',
    }
  ],
  '3': [
    {
      label: 'Hello',
      value: 'hello',
    },
    {
      label: 'World',
      value: 'world',
    }
  ]
};

const firstList = document.querySelector('#first-list');
const secondList = document.querySelector('#second-list');

function removeOptions(selectElement) {
  for (let i = selectElement.options.length - 1; i >= 0; i--) {
    selectElement.remove(i);
  }
}

// Update the second `<select>` based on the first's selection.
firstList.addEventListener('change', event => {
  const value = event.target.value;
  const options = optionData[value];
  
  removeOptions(secondList);
  
  for (const { label, value } of options) {
    const option = new Option(label, value);
    secondList.add(option);
  }
});
<label for="first-list">List One</label>
<select name="first-list" id="first-list">
  <option value="" selected disabled>Make a selection</option>
  <option value="1">First option</option>
  <option value="2">Second option</option>
  <option value="3">Third option</option>
</select>

<label for="second-list">List Two</label>
<select name="second-list" id="second-list">
  <option value="" selected disabled>No options yet</option>
</select>
wmvff8tz

wmvff8tz3#

您可以从js文件构建选择器:

const optionGroups = {
      "first": [
        { "text": "for first - 1", "value": 1 }
      ],
      "second": [
        { "text": "for second - 1", "value": 1 },
        { "text": "for second - 2", "value": 2 }
      ],
      "third": [
        { "text": "for third - 1", "value": 1 },
        { "text": "for third - 2", "value": 2 },
        { "text": "for third - 3", "value": 3 }
      ]
    },
      mainSelect = document.querySelector('#mainSelect'),
      secondarySelect = document.querySelector('#secondarySelect');

async function startWithMainSelect()
{
  for (let key of Object.keys(optionGroups))
  {
    const option = new Option(key);
    mainSelect.appendChild(option);
  }

  onChangeMainSelect();
}

function onChangeMainSelect()
{
  while (secondarySelect.firstChild)
    secondarySelect.firstChild.remove();

  for (let _option of optionGroups[mainSelect.value])
  {
    const option = new Option(_option.text, _option.value);
    secondarySelect.appendChild(option);
  }
}

mainSelect.addEventListener('change', onChangeMainSelect);

startWithMainSelect();
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>

  <h4>Main:</h4>

  <select id="mainSelect"></select>

  <br>

  <h4>Secondary:</h4>

  <select id="secondarySelect"></select>

  <script src="https://replit.com/public/js/replit-badge.js" theme="blue" defer></script>
  <script src="script.js"></script>
</body>

</html>

如果有很多选项,你可以把它们移到一个json文件中,然后从那里请求它们。

相关问题