首页 > 解决方案 > 无法让 JS 验证响应

问题描述

我正在尝试在按下提交时进行验证,但是在按下提交时不会弹出任何警报,我应该在此处收到字段为空等的警报。任何人都可以在我的代码中发现错误吗?由于我不太了解错误是什么,因此也尝试逐行进行验证。

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  var y = document.forms["myForm"]["comment"].value;
  if (x == "" && y == "") {
    alert("Please enter the blank fields!");
return false;
   } else if (x == "") {
    alert("Please enter your name!");
    return false;
   } else if (y == "") {
    alert("Please leave us a comment!");
    return false;
   } else {
   		if(document.getElementById('r5').checked) {
      	window.alert("Thank you")
      }
   }
}
.wrapper {
  display: inline-block;
}

.wrapper * {
  float: right;
}

.wrapper input {
  display: none;
}

label {
  font-size: 30px;
}

input:checked ~ label {
  color: red;
}
<!doctype html>
<html>

<link REL="StyleSheet"  TYPE="text/css" HREF="example2.css">

<body>

  <form id ="myForm">
    Name: <input type="text" id="fname">
    <br><br>
    Comment: <input type="input" id="comment">
    <br><br>
	


    <div class="wrapper">
      <input type="radio" id="r1" name="rg1">
      <label for="r1">&#10038;</label>
      <input type="radio" id="r2" name="rg1">
      <label for="r2">&#10038;</label>
      <input type="radio" id="r3" name="rg1">
      <label for="r3">&#10038;</label>
      <input type="radio" id="r4" name="rg1">
      <label for="r4">&#10038;</label>
      <input type="radio" id="r5" name="rg1">
      <label for="r5">&#10038;</label>
    </div>
	<br>

<button type="button" value="Submit" onclick="validateForm"()>Submit </button>
  </form>
  
</body>
<script src="jsreview.js"></script>
</html>

谢谢你检查这个

标签: javascripthtmlcssvalidation

解决方案


首先你的不链接提交和js函数提交按钮有时会默认表单提交,所以使用按钮类型而不是提交

在函数的第一行设置alert(),方便查看

<input type=button" value= SUBMIT" onclick="validateform()" >

或者

<button onclick="myFunction()">Click me</button>

<script> function myFunction() {  alert( "Hello World"); } </script>


推荐阅读