<html>
<head>
<title>JS Demo</title>
//下面定义了一段JS,功能是检查表单里面的username,如果是空的,就弹出一个报错窗口。使用getElementByName获取表单中的值。
<script type="text/javascript">
function check(){
var x=document.getElementsByName("username");
if(x==null){
alert("Please input username");
}
}
</script>
</head>
<body>
<form action="js.php" method="POST">
<input type="text" name="username"></input>
<input type="submit" name="sub" onsubmit="check()"></input>
</form>
</body>
</html>
就算username为空,JS也不报错。。什么原因啊
1、document.getElementsByName("username")返回的是一个数组,得到所有指定name值的节点,所以要用document.getElementsByName("username")[0],表示得到的第一个name值为username的节点;
2、要使用文本框的value(值)来判断文本框是不是为空,所以要先获取值,即x.value;
3、判断文本框的值是不是为空,要有null和""空串两种,所以要用x.value==null || x.value=="";
4、onsubmit是form的事件,要放在form标签里,且函数没有返回布尔值,就算为空,也是会提交表单,使用onsubmit="return false"可以阻止表单提交,而例子中函数返回true,或没有返回值(默认为true)时,可以正常提交;
<html>
<head>
<title>JS Demo</title>
//下面定义了一段JS,功能是检查表单里面的username,如果是空的,就弹出一个报错窗口。使用getElementByName获取表单中的值。
<script type="text/javascript">
function check(){
var x=document.getElementsByName("username")[0].value;
if(x==null || x==""){
alert("Please input username");
return false;
}
}
</script>
</head>
<body>
<form action="js.php" method="POST" onsubmit="return check()">
<input type="text" name="username"></input>
<input type="submit" name="sub"></input>
</form>
</body>
</html>
1.函数check里要判断一个控件是不是为空应该找到该控件并读取他的value属性如
var x=document.getElementById("username");
if(x.value==""){
alert("为空")
}
2.调用检查是要在<form action="js.php" method="POST" onsubmit="return check()">里
调用,注意onsubmit这里要用到 return check() ,check函数里验证通过返回true失败返回false
========================== 下面代码我已经帮你修改过了,可以验证了
<html>
<head>
<title>JS Demo</title>
//下面定义了一段JS,功能是检查表单里面的username,如果是空的,就弹出一个报错窗口。使用getElementByName获取表单中的值。
<script type="text/javascript">
function check(){
var x=document.getElementById("username");
if(x.value==""){
alert("Please input username");
return false
} else{
return true
}
}
</script>
</head>
<body>
<form action="js.php" method="POST" onsubmit="return check()">
<input type="text" name="username" id="username"></input>
<input type="submit" name="sub" ></input>
</form>
</body>
</html>
onsubmit事件应该写在表单form上。
应该是 var x=document.getElementById("username");
if(x.value==""){
alert("Please input username");
}
这样:
<html>
<head>
<title>JS Demo</title>
//下面定义了一段JS,功能是检查表单里面的username,如果是空的,就弹出一个报错窗口。使用getElementByName获取表单中的值。
<script type="text/javascript">
function check(){
var x=document.getElementById("username");
if(x.value==""){
alert("Please input username");
return false;
}
return true;
}
</script>
</head>
<body>
<form action="js.php" method="POST" onsubmit="return check();">
<input type="text" name="username" id="username"></input>
<input type="submit" name="sub" ></input>
</form>
</body>
</html>
你可以写成
if(x == undefined || x == null || x == "")
或是直接写成一个小函数
function isnull(str) {
return ((str == undefined || str == null || str == "") ? true : false);
}
然后调用isnull(x),如果真,就是空数据,如果false就是有值