监听表单提交事件
在jquery中,以下两种方式均可以监听到表单的提交事件。
$('#form1').submit(function(e){alert('监听到了表单提交事件')})
$('#form1').on('submit', function(e) {alert('监听到了表单提交事件')})
以下是这两种方式的例子:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="../lib/jquery.js"></script></head><body><form action="/login" id="f1"><input type="text" name="user_name"><input type="password" name="pwd"><button type="submit">提交</button></form><script>$(function() {//第一种方式// $('#f1').submit(function (e) {//return alert(1);// })//第二种方式$('#f1').on('submit', function() {return alert(2);})})</script></body></html>
上述的例子中,点击了提交之后,表单仍然会进行跳转,那么如何阻止表单的默认提交行为呢?
阻止表单默认提交行为
当监听到表单的提交事件以后,可以调用事件对象的 event.preventDefault() 函数,来阻止表单的提交和页面的跳转。实例如下:
第一种:
$('#form1').submit(function(e){e.preventDefault()})
第二种:
$('#form1').on('submit', function(e){e.preventDefault()})
例子:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="../lib/jquery.js"></script></head><body><form action="/login" id="f1"><input type="text" name="user_name"><input type="password" name="pwd"><button type="submit">提交</button></form><script>$(function() {//第一种方式$('#f1').submit(function (e) {e.preventDefault()return alert(1);})//第二种方式// $('#f1').on('submit', function(e) {//e.preventDefault()// })})</script></body></html>
快速获取表单中的数据:
1.$(selector).serialize()
serialize()函数的好处:可以一次性的获取到表单中所有元素的数据
如果我们想要使用serialize()快速获取表单元素的值,就要给每个输入框的name赋值,获取后返回的是键值对形式的数据。
例子:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="../lib/jquery.js"></script></head><body><form action="/login" id="f1"><input type="text" name="user_name"><input type="password" name="pwd"><button type="submit">提交</button></form><script>$(function() {//第一种方式// $('#f1').submit(function (e) {//e.preventDefault()//var data = $(this).serialize()//console.log(data)// })//第二种方式$('#f1').on('submit', function(e) {e.preventDefault()var data = $("#f1").serialize()console.log(data);})})</script></body></html>