小码哥的IT人生

onsubmit 事件

JavaScript基础 2022-06-08 12:03:06小码哥的IT人生shichen

onsubmit 事件

实例

提交表单时执行 JavaScript:

<form onsubmit="myFunction()">
  Enter name: <input type="text">
  <input type="submit">
</form>

完整实例:

<!DOCTYPE html>
<html>
<body>
<p>当您提交表单时,会触发提示文本的函数。</p>
<form action="/demo/html/action_page.php" onsubmit="myFunction()">
  Enter name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>
<script>
function myFunction() {
  alert("The form was submitted");
}
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

定义和用法

onsubmit 事件在提交表单时发生。

浏览器支持

事件 Chrome IE Firefox Safari Opera
onsubmit 支持 支持 支持 支持 支持

语法

在 HTML 中:

<element onsubmit="myScript">

完整实例:

<!DOCTYPE html>
<html>
<body>
<p>本例演示如何将 "onsubmit" 事件分配给 form 元素。</p>
<p>当您提交表单时,会触发提示文本的函数。</p>
<form action="/demo/html/action_page.php" onsubmit="myFunction()">
  Enter name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>
<script>
function myFunction() {
  alert("The form was submitted");
}
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

在 JavaScript 中:

object.onsubmit = function(){myScript};

完整实例:

<!DOCTYPE html>
<html>
<body>
<p>本例使用 HTML DOM 将 "onsubmit" 事件分配给 form 元素。</p>
<p>当您提交表单时,会触发提示文本的函数。</p>
<form id="myForm" action="/demo/html/action_page.php">
  Enter name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>
<script>
document.getElementById("myForm").onsubmit = function() {myFunction()};
function myFunction() {
  alert("The form was submitted");
}
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

在 JavaScript 中,使用 addEventListener() 方法:

object.addEventListener("submit", myScript);

完整实例:

<!DOCTYPE html>
<html>
<body>
<p>本例使用 addEventListener() 方法将 "submit" 事件附加到 form 元素。</p>
<p>当您提交表单时,会触发提示文本的函数。</p>
<form id="myForm" action="/demo/html/action_page.php">
  Enter name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>
<script>
document.getElementById("myForm").addEventListener("submit", myFunction);
function myFunction() {
  alert("The form was submitted");
}
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

注释:Internet Explorer 8 或更早的版本不支持 addEventListener() 方法

技术细节

冒泡: 支持
可取消: 支持
事件类型: Event
支持的 HTML 标签: <form>
DOM 版本: Level 2 Events

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024