19,表单的操作
19.1,表单的查询和修改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单</title>
<script>
window.onload=function () {
//获取input标签,通过value值查询表单的值
var username =document.getElementById('username');
console.log(username.value);
}
</script>
</head>
对于多选框,文本框,文本域,隐藏域可以直接通过设置value
而对于单选框,复选框,value
属性返回的永远是HTML预设的值,可以通过checked设置true或false
19.2,表单的提交
方式一:响应一个按钮的事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单</title>
<script>
function Submit() {
console.log("test");
}
</script>
</head>
<body>
<h1>用户注册</h1>
<form action="#">
<p>
用户名:
<input id ='username' type="text" name="username" maxlength="16" minlength="6" placeholder="请输入中文用户名" pattern="^[\u4e00-\u9fa5]{0,}$">
</p>
<p>
密码:
<input type="password" name="password" maxlength="16" minlength="6">
</p>
<button type="button" onclick="Submit()">提交</button>
</form>
</body>
</html>
方式二:响应form
的onsubmit`事件,在提交form时作修改:
<script>
function Submit() {
console.log("test");
return true;
}
</script>
<form action="#" onsubmit="Submit()">
<p>
用户名:
<input id ='username' type="text" name="username" maxlength="16" minlength="6" placeholder="请输入中文用户名" pattern="^[\u4e00-\u9fa5]{0,}$">
</p>
<p>
密码:
<input type="password" name="password" maxlength="16" minlength="6">
</p>
<botton type="submit">提交</botton>
</form>
注意要return true
来告诉浏览器继续提交,如果return false
,浏览器将不会继续提交form,这种情况通常对应用户输入有误,提示用户错误信息后终止提交form。
- 拓展:MD5结合hidden隐藏域设计密码框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单</title>
<script>
function Submit() {
var input_pwd =document.getElementById('password');
var md5_pwd=document.getElementById('md5-password');
//把用户的输入明文变为MD5,由于password没有设置name标签,而md5设置了name标签,不会被表单提交
//最后提交的就是md5中的加密数据,这样做比直接提交password,再进行加密更加安全
md5_pwd.value=MD5(input_pwd.value);
return true;//表单提交
}
</script>
</head>
<body>
<h1>用户注册</h1>
<form action="#" onsubmit="Submit()">
<p>
用户名:
<input id ='username' type="text" name="username" maxlength="16" minlength="6" placeholder="请输入中文用户名" pattern="^[\u4e00-\u9fa5]{0,}$">
</p>
<p>
密码:
<input type="password" id="password" maxlength="16" minlength="6">
<input type="hidden" id="MD5-password" name="md5-password">
</p>
<botton type="submit">提交</botton>
</form>
</body>
</html>