如何使用JavaScript验证下拉列表?

当我提交按钮而未选择任何选项时,则会显示错误。它可以工作,但是当我选择任何选项后点击提交时,这里的问题仍然存在。如果选择了选项,我将无法删除错误。

selected.Can anyone help me please

<form id="myForm">     
  <select  id="logs" data-placeholder="Type here to find device"
            name="tags[]"
            multiple
            class="chosen-select form-control"
            required>
    <option value="ASA"     > ASA     </option>
    <option value="ISE"     > ISE      </option>
    <option value="Windows" > Windows  </option>
    <option value="ATA"     > ATA      </option>
    <option value="Alliance"> Alliance </option>
    <option value="Proxy"   > Proxy    </option>
    <option value="Csp"     > CSP      </option>
  </select>
  <button type="submit">Submit</button>
  <p id="loggingError" style="color: red; font-size: small;"></p>
</form>
var logs = document.getElementById('logs');
var myForm = document.getElementById('myForm');

function loggingCheck(event)
{
  if (logs.selectedIndex == 0 )
  {
    document.getElementById('loggingError').innerHTML="Please select at least one logging devices";
    event.preventDefault();
  }
  else
  {
    document.getElementById('loggingError').innerHTML="";
  }
}

myForm.addEventListener('submit',loggingCheck);

评论
mex
mex
var logs = document.getElementById('logs');
var myForm = document.getElementById('myForm');

function loggingCheck(event) {

    if (logs.selectedIndex == 0) {
        document.getElementById('loggingError').innerHTML = "Please select at least one logging devices";
        event.preventDefault();
    } else {
        document.getElementById('loggingError').innerHTML = "";
    }
}

function changeCheck(event) {
    if (event.target.selectedIndex !== 0) document.getElementById('loggingError').innerHTML = "";
    else document.getElementById('loggingError').innerHTML = "Please select at least one logging devices";
}

myForm.addEventListener('submit', loggingCheck);
logs.addEventListener('change', changeCheck);
<form id="myForm">
  <select data-placeholder="Type here to find device" id="logs"  name="tags[]"  multiple class="chosen-select form-control" required>
    <option value="ASA" >ASA</option>
    <option value="ISE"> ISE</option>
    <option value="Windows"> Windows</option>
    <option value="ATA">ATA</option>
    <option value="Alliance"> Alliance</option>
    <option value="Proxy"> Proxy</option>
    <option value="Csp">  CSP</option>
  </select>
  <button type="submit">Submit</button>
  <p id="loggingError" style="color: red; font-size: small;"></p>
</form>
点赞
评论