表单onclick不起作用

时间:2017-04-13 20:59:16

标签: javascript html

我目前正在学习JS并尝试创建验证函数以查看字段是否为空。当我单击提交按钮时,我希望在Chrome中的JS控制台中看到一些内容,但我没有看到任何内容。为什么这不会回应到控制台?

var field1 = document.getElementById("field1");
var field2 = document.getElementById("field2");
var submitBtn = document.getElementById("submitBtn");

function validate() {

    if(field1 === "" || field2 === "") {
      console.log("Make sure all fields have been filled out correctly");
    } else {
      console.log("they are full");
    }
}  


<form action="" action="get">
     <input type="text" id="field1" name="field1" autocomplete="off" placeholder="Enter something"/>
     <input type="text" id="field2" name="field2" autocomplete="off" placeholder="Enter that thing again"/>
     <input type="submit" id="submitBtn" name="submitBtn" value="Submit" onclick="return validate()" />
</form>

2 个答案:

答案 0 :(得分:2)

如果您没有提交表单,只需将其设为按钮而不是提交.Submit使表单提交

请检查以下代码段

&#13;
&#13;
var submitBtn = document.getElementById("submitBtn");

function validate() {
var field1 = document.getElementById("field1").value;
var field2 = document.getElementById("field2").value;
  if (field1 === "" || field2 === "") {
    console.log("Make sure all fields have been filled out correctly");
  } else {
    console.log("they are full");
  }
}
&#13;
<form action="" action="get">
  <input type="text" id="field1" name="field1" autocomplete="off" placeholder="Enter something" />
  <input type="text" id="field2" name="field2" autocomplete="off" placeholder="Enter that thing again" />
  <input type="button" id="submitBtn" name="submitBtn" value="Submit" onclick="return validate()" />
</form>
&#13;
&#13;
&#13;

希望有所帮助

答案 1 :(得分:1)

表单提交将发回数据导致刷新,您可能无法在此之前看到控制台日志。

在console.log之后添加return false以捕获数据。此外,您需要使用element.value而不是element来获取值,同时将其与空条件进行比较。如果您想在验证通过时提交,请添加return true。

这是你的例子的工作小提琴:

&#13;
&#13;
<form action="" action="get">
     <input type="text" id="field1" name="field1" autocomplete="off" placeholder="Enter something"/>
     <input type="text" id="field2" name="field2" autocomplete="off" placeholder="Enter that thing again"/>
     <input type="submit" id="submitBtn" name="submitBtn" value="Submit" onclick="return validate()" />
</form>
<script>
var field1 = document.getElementById("field1");
var field2 = document.getElementById("field2");
var submitBtn = document.getElementById("submitBtn");

function validate() {

    if(field1.value === "" || field2.value === "") {
      console.log("Make sure all fields have been filled out correctly");
      return false;
    } else {
      console.log("they are full");
      return false;
    }
    
}  

</script>
&#13;
&#13;
&#13;