html 表单事件

html表单事件

onblur        当元素失去焦点时运行脚本
onchange    当元素改变时运行脚本
onfocus     当元素获得焦点时运行脚本
onselect    当选取元素时运行脚本
onsubmit    当提交表单时运行脚本

实例

onblur

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>表单事件</title>
<head>
    <script>
        function upperCase()
        {
            var x=document.getElementById("fname").value
            document.getElementById("fname").value=x.toUpperCase()
        }
    </script>
</head>
<body>

输入你的英文姓名(鼠标移开后小写会转换为大写): <input type="text" name="fname" id="fname" onblur="upperCase()">

</body>
</html>

onchange

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>表单事件</title>
    <script>
        function checkField(val)
        {
            alert("输入值已改变。新值: " + val);
        }
    </script>
</head>
<body>

输入文本: <input type="text" name="txt" value="Hello" onchange="checkField(this.value)">

</body>
</html>

onfocus

<!doctype html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>表单事件</title>
    <script type="text/javascript">
        function setStyle(id) {
            document.getElementById(id).style.backgroundColor = "#ccc"
        }
    </script>
</head>
<body>
name:<input type="text" id="name" onfocus="setStyle(this.id)"><br>
</body>
</html>

onselect

<!doctype html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>表单事件</title>
    <script type="text/javascript">
        function showMsg(id) {
            let text = document.getElementById(id);
            alert(text.value);
        }
    </script>
</head>
<body>
Some text: <input type="text" id="text1" value="选取我!!" onselect="showMsg(id)">
</body>
</html>

onsubmit

<!doctype html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>表单事件</title>
    <script type="text/javascript">
        function getValues() {
            let name = document.getElementById('name').value;
            let password = document.getElementById('password').value;
            alert("账号:" + name + ",密码:" + password);
        }
    </script>
</head>
<body>
<form action="#" onsubmit="getValues()">
    <lable>账号:</lable><input type="text" id="name" value=""/>
    <label>密码:</label><input type="password" id="password" value=""/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
上一篇:Typescript 泛型、泛型函数、泛型类、泛型接口


下一篇:JavaScript事件定义的3中方式