JavaScript表单如何验证dom选择器?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (71)

我很难将名为“color”的文本输入字段链接到一个条件语句。这是我的普通JS代码。

function validateForm(form) {
var x = document.forms["myForm"]["color"].value;
if (x === "red") {

    alert("Guess again!");
    return false;
}

}

这是html表单。

        <form name: "myForm" action="http://www.severien.com/grit/formecho.php" target="_blank" method="POST" onsubmit="return validateForm(this)">
        <fieldset>
            <legend>Personal Info:</legend>
            First Name:
            <br><input class="input" type="text" name="firstname" required min="2" maxlength="20"><br> Last Name:
            <br><input class="input" type="text" name="lastname" required min="2" maxlength="20"><br> Color:
            <br><input class="input" type="text" name="color" maxlength="20"> <br><b>
                Money</b> in my pocket:<br> <input type="number" name="money" required max="1000000"><br>
            <input type="submit" value="Submit">
        </fieldset>
    </form>
提问于
用户回答回答于

你的name属性form打错了,一定是name="myForm", 而不是name: "myForm".

function validateForm(form) {
  var x = document.forms["myForm"]["color"].value;
  if (x === "red") {

    alert("Guess again!");
    return false;
  }

}
<form name="myForm" action="http://www.severien.com/grit/formecho.php" target="_blank" method="POST" onsubmit="return validateForm(this)">
  <fieldset>
    <legend>Personal Info:</legend>
    First Name:
    <br><input class="input" type="text" name="firstname" required min="2" maxlength="20"><br> Last Name:
    <br><input class="input" type="text" name="lastname" required min="2" maxlength="20"><br> Color:
    <br><input class="input" type="text" name="color" maxlength="20"> <br><b>
                Money</b> in my pocket:<br> <input type="number" name="money" required max="1000000"><br>
    <input type="submit" value="Submit">
  </fieldset>
</form>

扫码关注云+社区

领取腾讯云代金券