簡體   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