无法获得JS验证以响应

时间:2019-03-17 03:21:36

标签: javascript html css validation

我正在尝试在按下“提交”时使验证生效,但是在按下“提交”时没有弹出警报,我应该在其中收到有关该字段为空等的警报。谁能在我的代码中发现错误?由于我不太了解错误所在,因此也尝试逐行进行验证。

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>

谢谢您检查

2 个答案:

答案 0 :(得分:0)

首先,您的非链接提交和js函数 而且,提交按钮有时会采用默认的表单提交方式,因此请使用按钮类型而不是提交

在函数的第一行中设置alert(),以便您轻松进行检查

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

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

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

答案 1 :(得分:0)

为您的表单提供一个ID,如下所示。

<form id="myForm">
<input type="submit" value="Submit" id="submit">

还要在您的javascript文件中添加以下行

document.getElementById('submit').addEventListener('click', validateForm);