下拉输入验证



我试图编码简单的输入验证,但它的行为很奇怪-当我选择的日期已经通过它是好的,当我选择有效的日期它是好的,但如果我选择无效的日期之后,它的行为就像它是有效的。我唯一的解决办法是重新加载页面,但这是愚蠢的…

const days = document.getElementById("day");
const time = document.getElementById("time");
const err = document.getElementById("err")
var today = new Date();
var hour = today.getHours();
var day = today.getDay();
function checkForValidInput()
{
  if (days.value > day)
  { 
    UI()
  }
  else if(days.value === day && time.value > hour)
  {
    
    UI()
  }
  else 
  {
    err.innerText = "Please select valid date / time";
  }
}

<div class="movie-container">
  <label> Select a Date:</label>
  <select onchange="checkForValidInput()" id="day">
    <option value="1">Monday</option>
    <option value="2">Tuesday</option>
    <option value="3">Wednesday</option>
    <option value="4">Thursday</option>
    <option value="5">Friday</option>
    <option value="6">Saturday</option>
    <option value="7">Sunday</option>
  </select>
</div>
<div class="movie-container">
  <label> Select a time:</label>
  <select onchange="checkForValidInput()" id="time">
    <option value="10">10:00</option>
    <option value="12">12:00</option>
    <option value="14">14:00</option>
    <option value="16">16:00</option>
    <option value="18">18:00</option>
    <option value="20">20:00</option>
  </select>
</div>

从你的代码,我看到没有函数重置元素时,下一个选择是有效的或不。你可以这样试试

const days = document.getElementById("day");
const time = document.getElementById("time");
const err = document.getElementById("err")
var today = new Date();
var hour = today.getHours();
var day = today.getDay();
function checkForValidInput() {
  if (days.value > day) {
    UI()
  } else if (days.value === day && time.value > hour) {
    UI()
  } else {
    err.innerText = "Please select valid date / time";
    // reset valid element because now invalid
    valid.innerText = "";
  }
}
function UI() {
  valid.innerText = "valid date / time";
  // when valid hide error message
  err.innerText = "";
}
<div class="movie-container">
  <label> Select a Date:</label>
  <select onchange="checkForValidInput()" id="day">
    <option value="1">Monday</option>
    <option value="2">Tuesday</option>
    <option value="3">Wednesday</option>
    <option value="4">Thursday</option>
    <option value="5">Friday</option>
    <option value="6">Saturday</option>
    <option value="7">Sunday</option>
  </select>
</div>
<div class="movie-container">
  <label> Select a time:</label>
  <select onchange="checkForValidInput()" id="time">
    <option value="10">10:00</option>
    <option value="12">12:00</option>
    <option value="14">14:00</option>
    <option value="16">16:00</option>
    <option value="18">18:00</option>
    <option value="20">20:00</option>
  </select>
</div>
<p id="err"></p>
<p id="valid"></p>

相关内容

  • 没有找到相关文章

最新更新