form表单阻止默认事件及获取值

阻止form的默认事件

方法1

采用行内js的onsubmit,那么实参必须使用保留的关键词event

复制代码
<form action="" id="aa" name="bb" onsubmit="cdma(event)">
  <input type="text" name="zhangsan" >
</form>

function cdma(event){
  event.preventDefault();
}

方法二

事件监听模式,那就e.preventDefault()即可

获取Form表单的方法

复制代码
<form action="" id="cc" name="dd">
  <input type="text" name="tx" id="txid">
  <input type="checkbox" id="ck" value="998" name="re" />
  <input type="checkbox" id="ck2" value="999" name="re" />
  <input type="file" name="fff">
  <button type="button">普通按钮</button>
  <button type="submit">提交</button>
</form>

document.forms获取,无论用id或name,效果一致

复制代码
document.forms['cc']
document.forms['dd']

方法1

获取表单中的某个值

复制代码
document.forms支持用name或id获取
document.forms['cc']['tx']
document.forms['cc']['txid']

方法二

遍历new FormData的实例可获取表单内对应的name属性和值

复制代码
document.forms['cc'].addEventListener('submit',function(e){ 
  e.preventDefault();
  new FormData(this).forEach(function(value,key){
    console.log('======value',value,key);
  })
})

方法三

formData实例内的get方法

注意:实参只能是name值,不能是id值

复制代码
document.forms['cc'].addEventListener('submit',function(e){ 
  e.preventDefault();
  var fd=new FormData(this)
  console.log('======fd',fd.get('tx'));
  console.log('======fd',fd.getAll('re'));
})

方法4

表单.elements[name或id]

复制代码
document.forms['cc'].addEventListener('submit',function(e){
  e.preventDefault();
  console.log('======',document.forms['cc'].elements['tx'].value);
  console.log('======',this.elements['tx'].value);
  console.log('======',this.elements['txid'].value);
})

获取同一个name值的checkbox

复制代码
采用数组形式
document.forms['cc'].addEventListener('submit',function(e){ 
  e.preventDefault();
  console.log('======',this.elements['re'][0].checked);
})

获取文件

复制代码
document.forms['cc'].addEventListener('submit',function(e){ 
  e.preventDefault();
  console.log('======',this.elements['fff'].files[0]);
})
相关推荐
QC班长3 小时前
Maven公司私库配置踩坑点
java·服务器·maven·intellij-idea
Makoto_Kimur3 小时前
java开发面试-AI Coding速成
java·开发语言
|晴 天|4 小时前
Vue 3 + TypeScript + Element Plus 博客系统开发总结与思考
前端·vue.js·typescript
wuqingshun3141594 小时前
说说mybatis的缓存机制
java·缓存·mybatis
空中海4 小时前
Kubernetes 生产实践、可观测性与扩展入门
java·贪心算法·kubernetes
猫3284 小时前
v-cloak
前端·javascript·vue.js
旷世奇才李先生4 小时前
Vue 3\+Vite\+Pinia实战:企业级前端项目架构设计
前端·javascript·vue.js
Devin~Y4 小时前
大厂Java面试实录:Spring Boot/Cloud、Kafka、Redis、K8s 与 Spring AI(RAG/Agent)三轮连环问
java·spring boot·redis·mysql·spring cloud·kafka·kubernetes
bLEd RING5 小时前
SpringBoot3.3.0集成Knife4j4.5.0实战
java
小松加哲5 小时前
Spring MVC 核心原理全解析
java·spring·mvc