js verification form fails and does not submit

There are two ways to verify the form:
**1.**Check whether the user password is entered by onsubmit()

<script>
	function ch()
	{
		var username = document.getElementById("name");//获取用户名的输入元素标签
		if(username.value=="")//如果用户名为空,提示并返回false
		{
			alert("用户名不能为空");
			return false;
		}
		pwd = document.getElementById("password");//获取密码的输入元素标签
		if(pwd.value=="")//如果密码为空,提示并返回false
		{
			alert("密码不能为空");
			return false;
		}
		return true;//只有用户名和密码都不为空才能返回true
	}
</script>
<form action="http://www.baidu.com" onsubmit="return ch()"> //返回false不提交
	<input id="name" placeholder="请输入用户名"/>
	<input id="password" type="password" placeholder="请输入密码"/>
	<input type="submit" value="登录"/>
</form>

2. Realized by document's submit()

<script>
	function check()
	{
		var element = document.getElementById("username");//获取用户名
		if(element.value=="")
		{
			alert("用户名不能为空");
			return;//如果用户名为空,提前返回方法,不提交
		}
		
		element = document.getElementById("userpass");
		if(element.value=="")
		{
			alert("密码不能为空");
			return;//如果密码为空,提前返回方法,不提交
		}
		document.getElementById("sub").submit();//方法进行到这里将form的action提交
	}
</script>
<form id="sub" action="http://www.taobao.com" >
	<input id="username" placeholder="请输入用户名"/>
	<input id="userpass" type="password" placeholder="请输入密码"/>
	<input type="button" value="登录" onclick="check()"/> //点击时调用chech()
</form>

Guess you like

Origin blog.csdn.net/weixin_43465609/article/details/109272164