简体   繁体   English

选择下拉菜单,使默认值不是可选选项

[英]Select Dropdown, make default Value not a selectable option

I have a form I want users to fill out.我有一个表单,希望用户填写。 I have an array of options they can choose from but I don't want any of them to be the default.我有一系列可供他们选择的选项,但我不希望它们中的任何一个成为默认选项。 I would like the drop down to say something like --Select-- .我希望下拉菜单显示类似--Select-- 的内容 Then when the users selects the dropdown, they can no longer select --Select-- .然后当用户选择下拉菜单时,他们不能再选择--Select--

I am using Redux forms and React-Bootstrap for the presentation.我正在使用 Redux 表单和 React-Bootstrap 进行演示。 I seen some answers on Stack Overflow, they say set the option to disable or add it as an option group.我在 Stack Overflow 上看到了一些答案,他们说设置选项以禁用或将其添加为选项组。 This resolve how it behaves when the dropdown opens but removes that option as a default option.这解决了当下拉菜单打开但删除该选项作为默认选项时的行为方式。

  let selectOptions = options.map((option, index) => {
    return (
      <option key={index} value={option}>
        {option}
      </option>
    );
  })
  const {value, ...inputs} = input
  
    return (
    <Aux>
      <Form.Label className="mb-1">{label}</Form.Label>
      {explanation && !readonly ? (
        <OverlayTrigger
          trigger="click"
          key={"right"}
          placement={"right"}
          overlay={
            <Popover id="popover-basic">
              <Popover.Header as="h3">{label}</Popover.Header>
              <Popover.Body>{explanation}</Popover.Body>
            </Popover>
          }
        >
          <i className="material-icons text-info align-top ml-2 cursor">help</i>
        </OverlayTrigger>
      ) : null}
      <Form.Control
        className={`${formStyle} ${validationStyle} ${noValidationStyle}`}
        disabled={readonly}
        as="select"
        placeholder="select"
        {...input}
        isInvalid={(touched || attempt) && !!error}
        isValid={!error}
      >
        {selectOptions}
      </Form.Control>

      {(touched || attempt) && !!error && !readonly ? (
        <Form.Control.Feedback type="invalid" className="animated fadeIn">
          {error}
        </Form.Control.Feedback>
      ) : (
        <span>{"\u00A0"}</span>
      )}
    </Aux>

The select element has a handy .remove method you can use. select 元素有一个方便的.remove方法可以使用。

For example:例如:

 const selectEl = document.querySelector("#dropdown") selectEl.addEventListener("change", removeDefault); function removeDefault(event){ const selectEl = event.target; if(selectEl.options[0].value == "myDefault"){ selectEl.remove(0); } }
 select { width: 9em; font-size: 2em; }
 <select id="dropdown"> <option value="myDefault">Choose Wisely</option> <option value="river">River</option> <option value="mal">Mal</option> <option value="zoe">Zoe</option> <option value="book">Shepherd Book</option> </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM