我的JavaScript验证程序不起作用。当我什么都不输入时,不会显示警报。另外,你们可以向我解释有关表单的操作方法是什么以及应该如何使用它吗?

<form method = "post" id = "my_form">
        <h1> Thank you for visiting our website! Please take some time to fill out our service questions! </h1>
        <h2> The ratings given are F, D, C, B and A. </h3>
        <h3> How would you rate the service that this webpage provides?? </h3>
        <input type = "text" font-size = "15px" id = "name">
        <h3> How would you rate the organization and usability of this webpage?? </h3>
        <input type = "text" font-size = "15px" id = "name">
        <h3> How would you rate the professionalism of this webpage?? </h3>
        <input type = "text" font-size = "15px" id = "name">
        <h3> How would you rate the overall look of this webpage??</h3>
        <input type = "text" font-size = "15px" id = "name">
        <br /><br />
        <input type = "submit" id = "submit" value = "submit" name = "submit">
        </form>

<script type = "text/javascript">
var my_form = document.getElementById("my_form");
my_form.addEventListener("submit", function(event) {
    var name = document.getElementById("name").value;
    var tomatch = /[a-f]/i;
    if (!tomatch.test(name)) {
    event.preventDefault();
    window.alert("The name can only contain letters from a-f");
    }
}. false);
</script>

最佳答案

您有多个具有相同ID的输入,并且此处的语法错误不正确

my_form.addEventListener("submit", function(event) {
    // bunch of code...
}. false); // <-- not dot, but comma


检查以下解决方案



document.getElementById("my_form").onsubmit = function(event) {
  var tomatch = /[a-f]/i;

  //var name = document.getElementById("name").value;
  // you can also get value like this
  var name = document.forms.my_form.name.value

  if (!tomatch.test(name)) {
    event.preventDefault();
    window.alert("The name can only contain letters from a-f");
  }
}

<form method="post" id="my_form" method="post" action"/my-url">
  <input type="text" font-size="15px" id="name">
  <input type="submit" id="submit" value="submit" name="submit">
</form>

09-27 16:40