Javascript表单验证

时间:2014-10-25 11:36:28

标签: javascript html forms validation

所以我尝试的是显示错误“必须填写名字”作为一个名为“check”的文本,而不是作为警告...... 请帮忙:)

  <html>
  <body>

 <form name="myForm" action="page.html" onsubmit="return validateForm()" method="post">
  First name: <input type="text" name="box>
 <input type="submit" value="Submit">
</form> 
<p id="check"></p>


<script>

function validateForm() {
var x = document.forms["myForm"]["box"].value;
if (x == null || x == "") {
    alert("First name must be filled out") ="check"; // I tried to send alert as text... 
    return false;
 }
 } 

  </script>

  </body>
   </html> 

提前致谢!

2 个答案:

答案 0 :(得分:3)

更改

alert("First name must be filled out") ="check";

document.getElementById('check').innerHTML = 'First name must be filled out';

答案 1 :(得分:2)

作为纯 Javascript 解决方案,您可以使用以下代码替换alert

document.getElementById('check').innerHTML = "First name must be filled out";


jQuery 中,您可以尝试:

$( "#check" ).html( 'First name must be filled out' );