js 表單操作
表單通常通過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有相容性問題,這種方法可以解決相容性問題