form表单实例
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>javascript form表单</title> 6 </head> 7 <script> 8 function validataForm(form){ 9 // var x=document.forms["myForm"]["fname"].value 10 var y=form.fname.value 11 console.log(y) 12 if(x==null || x==""){ 13 alert("请输入您的姓名") 14 return false 15 } 16 } 17 </script> 18 <body> 19 <form action="JavaScript 条件运算符.html" name="myForm" onsubmit="return validataForm(this)" method="post"> 20 姓名:<input type="text" name="fname" required="required"> 21 <input type="submit" value="提交"> 22 </form> 23 </body> 24 </html>
JavaScript验证输入的数字
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>javascript form表单验证输入</title> 6 </head> 7 <body> 8 <h1>javascript 验证输入</h1> 9 <p>请输入1~10之间的数字。</p> 10 <input type="text" id="num"> 11 <button type="button" onclick="myFunction()">提交</button> 12 <p id="demo"></p> 13 <script> 14 function myFunction(){ 15 var x, text 16 // 获取输入的num值并赋值给x 17 x = document.getElementById("num").value; 18 // 如果 x不是数字或x<1或x>10 返回输入错误 19 if(isNaN(x) || x<1 || x>10){ 20 text = "输入错误" 21 } 22 // 否则返回输入正确 23 else{ 24 text = "输入正确" 25 } 26 document.getElementById("demo").innerHTML=text; 27 } 28 </script> 29 </body> 30 </html>
html自动表单验证
html表单也可以通过浏览器自动验证。
如果表单中某字段为空,可以通过required属性阻止表单提交
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>javascript form表单</title> 6 </head> 7 <script> 8 function validataForm(form){ 9 // var x=document.forms["myForm"]["fname"].value 10 var y=form.fname.value 11 console.log(y) 12 if(x==null || x==""){ 13 alert("请输入您的姓名") 14 return false 15 } 16 } 17 </script> 18 <body> 19 <form action="JavaScript 条件运算符.html" name="myForm" onsubmit="return validataForm(this)" method="post"> 20 //required 属性控制该字段是否为空 21 姓名:<input type="text" name="fname" required="required"> 22 <input type="submit" value="提交"> 23 </form> 24 </body> 25 </html>
标签:form,text,JavaScript,value,表单,var,输入 From: https://www.cnblogs.com/wenzm/p/17047934.html