表单通常通过name获取元素
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
<script>
window.onload = function(){
var oForm = document.getElementById('form1');
alert(oForm.text1.value);
}
</script>
</head>
<body>
<form id="form1">
<input type="text" name="text1" id="text1" value="内容" />
</form>
</body>
</html>
onchange:当值发生改变的时候触发
text:当光标离开的时候如果内容有变化就触发
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
<script>
window.onload = function(){
var oForm = document.getElementById('form1');
oForm.text1.onchange = function(){
alert(this.value);
}
}
</script>
</head>
<body>
<form id="form1">
<input type="text" name="text1" id="text1" value="内容" />
</form>
</body>
</html>
性别:同组中只能选择一个
<input type="radio" name="sex" value="男" />男
<input type="radio" name="sex" value="女" />女
radio/checkbox:都有默认选中checked
radio/checkbox:标准下点击的时候只要值变了那么就会触发
非标准下焦点离开的时候如果值变了就会触发
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
<script>
window.onload = function(){
var oForm = document.getElementById('form1');
alert(oForm.sex);
oForm.sex[0].onchange = function(){
alert(1);
}
}
</script>
</head>
<body>
<form id="form1">
<input type="text" name="text1" id="text1" value="内容" />
<input type="radio" name="sex" value="男" />男
<input type="radio" name="sex" value="女" />女
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
<script>
window.onload = function(){
var oForm = document.getElementById('form1');
oForm.city.onchange = function(){
alert(this.value);
}
}
</script>
</head>
<body>
<form id="form1">
<select name="city">
<option value="">请选择城市</option>
<option value="北京">北京</option>
<option value="上海">上海</option>
</select>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
<script>
window.onload = function(){
var oForm = document.getElementById('form1');
oForm.btn.onclick = function(){
for(var i=0;i<oForm.sex.length;i++){
if(oForm.sex[i].checked){
alert(oForm.sex[i].value + '是选中了');
}else{
alert(oForm.sex[i].value + '是非选中状态');
}
}
for(var i=0;i<oForm.a.length;i++){
if(oForm.a[i].checked){
alert(oForm.a[i].value + '是选中了');
}else{
alert(oForm.a[i].value + '是非选中状态');
}
}
}
}
</script>
</head>
<body>
<form id="form1">
<input type="text" name="text1" id="text1" value="内容" />
<input type="radio" name="sex" value="男" />男
<input type="radio" name="sex" value="女" />女
<input type="checkbox" name="a" value="html" />html
<input type="checkbox" name="a" value="css" />css
<input type="checkbox" name="a" value="js" />js
<select name="city">
<option value="">请选择城市</option>
<option value="北京">北京</option>
<option value="上海">上海</option>
</select>
<input type="button" value="按钮" name="btn" />
</form>
</body>
</html>
onchange有兼容性问题,这种方法可以解决兼容性问题