Blogger Information
Blog 47
fans 0
comment 3
visits 44845
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
表单元素及表单事件
江流
Original
805 people have browsed it

表单元素及表单事件

表单元素可以通过document.forms获取表单集合,后边跟一个表单的id值,选定具体表单,也可以使用下标。
表单有默认的提交行为,可以在表单元素中加入onsubmit=”return false”,设置submit属性,取消器提交行为,也可以在javascipt代码中使用preventDefault()函数取消提交行为。

  • html
  1. <!-- onsubmit="return false" 禁用表单默认提交行为-->
  2. <form id="register" action="" onsubmit="return false">
  3. <div>
  4. <label for="username">用户名:</label>
  5. <input
  6. type="text"
  7. name="username"
  8. placeholder="用户名不能少于6位字符"
  9. required
  10. />
  11. </div>
  12. <button>注册</button>
  13. </form>
  • javascript
  1. // 表单选择器
  2. const form = document.forms.register;
  3. console.log(form.username.value);
  4. const btn = document.querySelector("button");
  5. // 监听事件
  6. btn.addEventListener("click", ($) => {
  7. // 表单元素可以通过元素的name属性获取
  8. //用户名长度
  9. let len = form.username.value.length;
  10. if (len < 6) {
  11. alert("用户名少于8位");
  12. return false;
  13. }
  14. });
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:尽量当天的作业,全部提交到一个博客中, 方便统计完成情况
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post