1、获取表单元素
通过form.name属性,获取到对应的元素
<form action="" id="form">
<input type="text" name="uname">
<input type="password" name="pass">
<input type="checkbox" name="aihao">
<input type="checkbox" name="aihao">
<input type="checkbox" name="aihao">
</form>
<script>
// 通过 form.name 可以获取到相对应的表单元素
var form = document.getElementById('form');
var uname = form.uname;
var pass = form.pass;
var ah = form.aihao;
console.log(uname, pass);
console.log(ah);
</script>
<form action="" id="form">
<input type="text" name="uname">
<input type="password" name="pass">
<br>
<br>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
<script>
var form = document.getElementById('form');
var uname = form.uname;
var pass = form.pass;
// 提交事件
// 点击提交按钮,会触发这个提交事件,如果在这个事件中,返回false,则可以阻止提交
// 可以对表单进行验证
form.onsubmit = function () {
if (!uname.value || !pass.value) {
alert('用户名和密码必须填写')
return false;
}
}
// 重置事件
// 点击重置按钮时,会触发这个重置事件,如果在这个事件中,返回false,则可以阻止重置
form.onreset = function () {
// var tag = confirm('是否真的重置?');
// if (tag) {
// return true;
// } else {
// return false;
// }
return confirm('是否真的重置?');
}
</script>
3、表单方法
form.submit() // 提交方法
form.reset() // 重置方法
<form action="" id="form">
<input type="text" name="uname">
<input type="password" name="pass">
</form>
<span>提交</span>
<span>重置</span>
<script>
var form = document.getElementById('form');
var span = document.querySelectorAll('span');
// 提交方法
span[0].onclick = function () {
form.submit();
}
// 重置方法
span[1].onclick = function () {
form.reset();
}
</script>
<input type="text">
<script>
var input = document.querySelector('input');
// 得焦事件
input.onfocus = function () {
this.style.backgroundColor = 'red';
}
// 失焦事件
input.onblur = function () {
this.style.backgroundColor = '';
}
// ----------------------------
// 3s钟得到焦点,接着3s以后又失去焦点
setTimeout(function () {
input.focus();
setTimeout(function () {
input.blur();
}, 3000);
}, 3000);
</script>
<input type="text">
<script>
var input = document.querySelector('input');
// 内容只要发生变化时触发的事件
// IE8及以下不支持
input.oninput = function () {
console.log(this.value);
}
// IE8及以下支持
input.onpropertychange = function () {
console.log(this.value);
}
</script>
<input type="text">
<input type="checkbox">
<script>
// 表单元素.onchange = 函数
// 失去焦点时内容发生变化时触发的事件
var input = document.querySelectorAll('input');
// 针对单行文本框
input[0].onchange = function () {
console.log(this.value);
}
// change主要针对单选和复选
input[1].onchange = function () {
console.log(this.checked);
}
</script>