Demo: Validate a Listbox Before Submission

Select one language, then submit the form. Leaving the placeholder selected shows the custom validation message without submitting.

Submit the form after choosing an option.

JavaScript

document.addEventListener("DOMContentLoaded", () => {
  const form = document.getElementById("f1");
  const list = document.getElementById("l1");
  const message = document.getElementById("my_msg");
  form.addEventListener("submit", (event) => {
    if (list.value === "") {
      event.preventDefault();
      message.textContent = "Select one option before submitting.";
      message.className = "alert alert-warning mt-2";
      list.focus();
    }
  });
});

HTML

<form id="f1" action="listbox-validation-demock.php" method="post">
  <select id="l1" name="Category" required>
    <option value="">Select One</option>
    <option value="PHP">PHP</option>
    <option value="JavaScript">JavaScript</option>
  </select>
  <div id="my_msg" aria-live="polite"></div>
  <button type="submit">Submit Form</button>
</form>

Return to listbox validation




Subscribe to our YouTube Channel here



plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer