<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>表单事件</title>
</head>
<body>
<!-- 1.表单值的获取:name属性
2.onchange()事件,事件发生变化后
2.1text/textarea -->
<h3>登录</h3>
<form action="" id="login" name="login">
<p>
<label for="username">
用户名
</label>
<input type="text" name="username" id="username" value="admin">
</p>
<!-- 单选按钮 -->
<p>
<input type="radio" name="gender" value="male" id="male" checked><label for="male">男</label>
<input type="radio" name="gender" value="female" id="female"><label for="female">女</label>
</p>
<!-- 复选框 -->
<p>
<input type="checkbox" name="hoppy[]" value="game" id="game" checked><label for="game">打游戏</label>
<input type="checkbox" name="hoppy[]" value="book" id="book"><label for="book">读书</label>
</p>
<!-- 下拉框 -->
<p>
<select name="area" value="与option中的selected一致">
<!-- 默认选中第一项 -->
<option value="shushan">蜀山区</option>
<option value="luyang">庐阳区</option>
<option value="baohe" selected>包河区</option>
</select>
</p>
</form>
<script type="text/javascript">
var login = document.getElementById('login');
// var login=document.getElementsByTagName('form')[0];
// var login=document.forms['login'];
// var login=document.forms[0];
// login.username.onchange = function() {
//
// }
for (var i = 0; i < login.gender.length; i++) {
//this是发生事件的当前元素(上下文对象)
//重复点击一个按钮不会触发,只有改变选择才会有效
login.gender[i].onchange = function() {
console.log(this.value);
}
}
// 复选框与单选按钮也是类似的,也是返回一组相关元素
for (var i = 0; i < login['hoppy[]'].length; i++) {
login['hoppy[]'][i].onchange = function() {
console.log(this.value);
}
}
login.area.onchange=function(){
console.log(this.value);
}
</script>
</body>
</html>