在 Select 菜单中编辑的值 Select 未发送到服务器

Value Selected in Select Menu Not Being Sent To the Server

(后端开发人员在这里尝试做一些前端开发)

我有一个简单的 HTML 表单,其中包含一些文本字段输入和一个 select 菜单。提交表单后,我看到文本字段值访问了 Web 服务器,但我没有看到 select 菜单的值访问了服务器。 select 菜单的代码是:

<div class="mdc-select mdc-select--outlined mdc-select--with-leading-icon role-list">
  <i class="material-icons mdc-select__icon" tabindex="0" role="button">work_outline</i>
  <div class="mdc-select__anchor role-width-class">
    <i class="mdc-select__dropdown-icon"></i>
    <div id="role" class="mdc-select__selected-text" aria-labelledby="roles-select-label"></div>
    <div class="mdc-notched-outline">
      <div class="mdc-notched-outline__leading"></div>
      <div class="mdc-notched-outline__notch">
        <label id="roles-select-label" class="mdc-floating-label">Role</label>
      </div>
      <div class="mdc-notched-outline__trailing"></div>
    </div>
  </div>

  <div class="mdc-select__menu mdc-menu mdc-menu-surface role">
    <ul class="mdc-list">
      <li class="mdc-list-item" data-value="0">
        Painter
      </li>
      <li class="mdc-list-item" data-value="1">
        Electrician
      </li>
      <li class="mdc-list-item" data-value="2">
        Decorator
      </li>
    </ul>
  </div>
</div>

select 菜单是 material 设计组件,如 here 所述。

我关联到此组件的 Javascript 是:

mdc.select.MDCSelect.attachTo(document.querySelector('.role-list'));

const role = new mdc.select.MDCSelect(document.querySelector('.role-list'));

role.listen('change', () => {
    alert(`Selected option at index ${role.selectedIndex} with value "${role.value}"`);
});

我有几个问题:

  1. 我应该使用 <li> 而不是 <option> - 上面的代码遵循网站上显示的示例。
  2. 是否应该有 name 属性?

创建隐藏输入:

<input type="hidden" name="my_select" id="my_select" value="">

然后将值存储在那里:

mdc.select.MDCSelect.attachTo(document.querySelector('.role-list'));

const role = new mdc.select.MDCSelect(document.querySelector('.role-list'));

role.listen('change', () => {
    document.getElementById('my_select').value = role.value;
});

附加信息部分的 material documentation 中有对此的新更新。它建议做与接受的答案相同的事情,但没有 JavaScript.

只是想把它放在那里以供参考此内容的新人使用。

Select with hidden input (for HTML forms)

For convenient submission of Select's value in HTML forms, a hidden input element may be added under the root element. The component will synchronize its value with that of the hidden input.

<div class="mdc-select mdc-select--filled demo-width-class">
  <div class="mdc-select__anchor">
    <!-- Rest of component omitted for brevity -->
  </div>
</div>