繁体   English   中英

自定义 Select 的自定义验证和错误消息

[英]Custom Validation and error message for Custom Select

function setError(input, message) {
  const form = input.parentElement;
  const small = form.querySelector('small');
  small.innerText = message;
  form.className = 'inputfield error';
}

function setSuccess(input) {
  const form = input.parentElement;
  form.className = 'inputfield success';
}

这是我的 JavaScript 代码,用于为输入字段设置错误或成功。 它对输入工作正常。

但是当我尝试为自定义 select 盒子应用相同的代码时,它不起作用。 我是 web 开发的新手,因此我们将不胜感激。

参考输入字段代码:

  <div class="inputfield">
    <label>NID</label>
    <input type="text" value="" class="input" id="nid" onkeyup="checkNid()">
    <small>Error Message</small>
  </div>

参考自定义 Select 代码:

  <div class="inputfield">
      <label>Gender</label>
      <div class="custom_select">
        <select name="gender" id="gender">
          <option value="">Select</option>
          <option value="male">Male</option>
          <option value="female">Female</option>
          <option value="Others">Others</option>
        </select>
      </div>
      <small>Error Message</small>
    </div> 

这是 output。 我也期待 select 字段出现相同类型的错误消息: output

将您的参考自定义 Select 代码替换为:

<div>
  <label>Gender</label>
  <div class="inputfield custom_select">
    <select name="gender" id="gender">
      <option value="">Select</option>
      <option value="male">Male</option>
      <option value="female">Female</option>
      <option value="Others">Others</option>
    </select>
     <small>Error Message</small>
  </div>
</div> 

如果您共享了 CSS 文件,我会建议如何更好地设置它的样式。

 .wrapper .form .inputfield .custom_select {
  position: relative;
  width: 100%;
  height: 37px;
}

.wrapper .form .inputfield .custom_select:before {
  content: '';
  position: absolute;
  top: 12px;
  right: 10px;
  border: 8px solid;
  border-color: #d5dbd9 transparent transparent transparent;
  pointer-events: none;
}

.wrapper .form .inputfield .custom_select select {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: none;
  width: 100%;
  height: 100%;
  border: 0px;
  padding: 8px 10px;
  font-size: 15px;
  border: 1px solid #d5dbd9;
  border-radius: 3px;
}

这里是自定义选择的 css

暂无
暂无

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

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