search
HomeWeb Front-endJS TutorialJavaScript form processing implementation code_basic knowledge

One form introduction

In HTML, the form is represented by the

element, while in JavaScript, the form corresponds to the HTMLFormElement type;

//HTMLFormElement inherits HTMLElement; therefore it has the default attributes of HTML elements, and also has its own attributes and methods;
HTMLFormElement properties and methods
Attribute or method description
acceptCharset The character set that the server can handle;
action accepts the requested URL;
elements A collection of all controls in the form;
enctype requested encoding type;
length The number of controls in the form;
method The type of HTTP request to send, usually 'get' or 'post';
name The name of the form;
target window name used to send requests and receive responses;
reset() resets all forms;
submit() submit the form;

1. Get the form object;
document.getElementById('myForm'); // Use ID to get the

element;
document.getElementsByTagName('form')[0]; // Use to get the first element in the form element collection;
document.forms[0]; // Use the numeric subscript of forms to get the element;
document.forms['myForm']; // Use the form's name subscript to get the element;

2. Submit the form

(1). Through the event object, you can prevent the default behavior of submit. The default behavior of the submit event is to jump to the specified page with data;

Copy code The code is as follows:

​ addEvent(fm,'submit',function(evt){
          preDef(evt);
});

(2). We can use the submit() method to customize the triggering of the submit event; that is, it is not necessary to click the submit button to submit;

Copy code The code is as follows:

If(e.ctrlKey && e.keyCode ==13){
                                                                                                                                                                                              }
// PS: Try to avoid using names such as name="submit" or id="submit" in the form. This will conflict with the submit() method and result in failure to submit;

(3). Repeat submission

// When a piece of data is submitted to the server, there will be a delay and no reflection for a long time, causing the user to keep clicking submit,
// As a result, many same requests are submitted repeatedly, or errors are caused or multiple pieces of the same information are written to the database;

Copy code The code is as follows:
AddEvent(fm,'submit',function(evt){ // Simulate server delay;
          preDef(evt);
Settimeout (function () {// 3 seconds before processing submitted to the server;
                                 fm.submit();
},3000);
});
// Solve duplicate submission plan

// The first type: disable the click button immediately after submission;
Document.getElementById('sub').disabled = true; // Disable the button;
// Second type: After submission, cancel subsequent form submission operations;
var flag = false; var flag = false; //Set a listening variable;
if(flag == true)return; // If it exists, return the exit event;
flag = true; // Otherwise, it must be the first time, change the value of the listening variable;

3. Reset form

// 用户点击重置按钮时,表单会被初始化;
// 虽然这个按钮还得以保留,但目前Web已经很少去使用了;因为用户填好信息后,不小心点击了重置就会全部清空,用户体验极差;
// 有两种方法调用reset事件:第一个就是直接type="reset"即可;第二个就是使用fm.reset()方法调用;
  <input type="reset" value="重置" />          // 不需要JS代码即可实现;
  addEvent(document,'click',function(){
    fm.reset();                   // 使用JS方法实现重置;
  });

4.表单字段

// 表单处理中,建议使用HTMLDOM,它有自己的elements属性,该属性是表单中所有元素的集合;
    fm.elements[0];                                     // 获取第一个表单字段元素;
    fm.elements['user'];                                // 获取name值是user的表单字段元素;
    fm.elements.length;                                 // 获取所有表单字段的数量;

(1).共有的表单字段属性
// 除了

元素之外,所有表单字段都拥有相同的一组属性;
属性                     说明
disabled         布尔值,表示当前字段是否被禁用;
form             指向当前字段所属表单的指针,只读;
name             当前字段的名称;
readOnly         布尔值,表示当前字段是否只读;
tabIndex         表示当前字段的切换;
type             当前字段的类型;
value            当前字段的值;
    fm.elements[0].value;                               // 获取和设置value;
    fm.elements[0].disabled = true;                     // 禁用当前字段;

(2).共有的表单字段方法
方法                     说明
focus()          将焦点定位到表单字段里;
blur()           从元素中将焦点移走;

(3).共有的表单字段事件


事件名                     说明
blur             当字段失去焦点时触发;
change           对于

// 利用focus事件修改文本框的背景色;
// 利用change事件在用户输入非数值字符时再次修改背景色;
  var bextbox = document.forms[0].elements[0];
  EventUtil.addHandler(textbox,'focus',function(evt){
    evt = EventUtil.getEvent(evt);
    var target = EventUtil.getTarget(evt);
    if(target.style.backgroundColor != 'red'){
      target.style.backgroundColor = 'yellow';    // 选中状态时文本框的背景是黄色;
    }
  });

  EventUtil.addHandler(textbox,'blur',function(evt){   // 失去焦点事件;
    evt = EventUtil.getEvent(evt);
    var target = EventUtil.getTarget(evt);
    if(/[^\d]/.test(target.value)){           // 输入非数值字符时;
      target.style.backgroundColor = 'red';      // 文本框背景变成红色;
    }else{
      target.style.backgroundColor = '';
    }
  });

  EventUtil.addHandler(textbox,'change',function(evt){  // 改变value值且失去焦点事件;
    evt = EventUtil.getEvent(evt);
    var target = EventUtil.getTarget(evt);
    if(/[^\d]/.test(target.value)){
      target.style.backgroundColor = 'red';      // 文本框变成红色;
    }else{
      target.style.backgroundColor = '';
    }
  });

二 文本框脚本
// 在HTML中,有两种方式来表现文本框:

// 一种是单行文本框;

// 一种是多行文本框

1.获取value值

// 虽然在字面上有value值,而

// defaultValue:得到原本的value值;不会因为值的改变而变化;
    alert(textField.defaultValue);                        // 得到最初设置的value值;

2.选择文本

// 使用select()方法,可以将文本框里的内容选中,并将焦点设置到文本框中;
  textField.select();                   // 在文本框获得焦点时选择其所有文本;

// 选取部分文本
// 在使用文本框内容的时候,我们有时要直接选定部分文本,这个行为还没有标准;
// Firefox的解决方案是:setSelectionRange()方法;它接受两个参数:索引和长度;
  textField.setSelectionRange(0,1);            // 选择第一个字符;
  textField.setSelectionRange(0,textField.value.length);  // 选择全部; 
  // IE8以下不支持这种写法,可以使用IE的范围操作代替;
  var range = textField.createTextRange();         // 创建一个文本范围对象;
  range.collapse(true);                  // 将指针移动到起点;
  range.moveStart('character',0);             // 移动指针,character表示逐字移动;
  range.moveEnd('character',1);              // 移动终点;
  range.select();                     // 焦点选定;

// 选择部分文本兼容函数
  function selectText(text,start,stop){
    if(text.setSelectionRange){
      text.setSelectionRange(start,stop);
      text.focus();
    }else if(text.createTextRange){
      var range = text.createTextRange();
      range.collapse(true);
      range.moveStart('character',start);
      range.moveEnd('character',sotp-start);
      range.select();
    }
  }

// 与select()方法对应的,是一个select事件,可以选中文本框文本后触发;
  addEvent(textField,'select',function(){
    alert(this.value);                // IE事件需要传递this才可以这么写;
  });
// 获得选择的文本
// Firefox提供了两个属性:selectionStart和selectionEnd;
  addEvent(textField,'select',function(){
    alert(this.value.substring(this.selectionStart,this.selectionEnd));
  });
  // IE8以下,提供了另一个方案:selection对象,属于document;
  // 这个对象保存着用户在整个文档范围内选择的文本信息;
  // 兼容函数
  function getSelecText(text){
    if(typeof text.selectioinStart =='number'){     // 非IE;
      return text.value.substring(text.selectionStart,text.selectionEnd);
    }else if(document.selection){            // IE;
      return document.selection.createRange().text;  // 获取IE选择的文本;
    }
  }
  // PS:存在问题:IE在触发select事件的时候,在选择一个字符后立即触发,而其他浏览器是选择想要的字符后释放鼠标键时再触发;
  // 所以使用alert()的话,导致跨浏览器的不兼容;
  // 所以我们可以通过将得到的选择文本赋值给别的对象;
  addEvent(textField,'select',function(){
    // alert(getSelecText(this));            // 导致用户行为结果不一致; 
    document.getElementById('box').innerHTML = getSelecText(this);
  })

3.过滤输入

// 为了使文本框输入指定的字符,我们必须对输入进文本框的字符进行验证;
  addEvent(areaField,'keypress',function(evt){
    var e = evt || window.event;
    var charCode = getCharCode(evt);      // 得到字符编码;
    if(!/\d/.test(String.formCharCode(charCode)) && charCode>9 && !e.ctrlKey){
      preDef(evt);              // 条件阻止默认;
    }
  });
  // PS:前半段条件判断只有数字才可以输入,导致常规按键,比如光标键/退格键/删除键等无法使用;
  // 部分浏览器比如Firefox,需要解放这些键,而非字符触发的编码均为0;
  // 在Safari3之前的浏览器,也会被阻止,而它对应的字符编码全部为8,所以最后加上charCode>9的判断;
  // 确保用户没有按下ctrl键;
// 阻止文本框裁剪/复制和粘贴;
事件名        说明
copy     在发生复制操作时触发;
cut      在发生裁剪操作时触发;
paste     在发生粘贴操作时触发;
beforecopy  在发生复制操作时触发;
beforecut   在发生裁剪操作时触发;
beforepaste  在发生粘贴操作时触发;
// 如果我们想要禁用裁剪/复制/粘贴,那么可以阻止默认行为即可;
  addEvent(areaField,'cut',function(evt){
    preDef(evt);
  });
  addEvent(areaField,'copy',function(evt){
    preDef(evt);
  });
  addEvent(areaField,'paste',function(evt){
    preDef(evt);
  });

// 最后一个影响输入的因素,就是:输入法;
// 中文输入法,它的原理是在输入法面板上先储存文本,按下回车就写入英文文本,按下空格就写入中文文本;
// 解决方案:通过CSS来禁止调出输入法;
  style='ime-mode:disabled';          // CSS直接编写;
  areaField.style.imeMode='disabled';      // 在JS中设置;
  // PS:Chrome无法禁止输入法调出,所以,最后使用正则验证已输入的文本;
  addEvent(areaField,'keyup',function(evt){
    this.value = this.value.replace(/[^\d]/g,'');  // 把非数字都替换成空;
  });

4.自动切换焦点

// 为了增加表单字段的易用性,很多字段在满足一定条件时(比如长度),就会自动切换到下一个字段上继续填写;
  <input type='text' name='user1' maxlength='1'/>    // 只能写1个;
  <input type='text' name='user2' maxlength='2'/>   
  <input type='text' name='user3' maxlength='3'/>
  function tabForward(evt){
    var e = evt || window.event;
    var target = getTarget(evt);
    // 判断当前长度是否和指定长度一致;
    if(target.value.length == target.maxLength){
      // 遍历所有字段;
      for(var i=0; i<fm.elements.length; i++){
        // 找到当前字段;
        if(fm.elements[i]==target){
          // 就把焦点移入下一个字段;
          if(fm.elements[i+1]){
            fm.elements[i+1].focus();
          }
          // 中途返回;
          return;
        }
      }
    }
  }

三 选择框脚本

选择框是通过

HTMLSelectElement对象

属性/方法                 说明
add(new,rel)        插入新元素,并指定位置;
multiple            布尔值,是否允许多项选择;
options            

// 在DOM中,每个

var city = fm.elements['city'];      // HTMLSelectElement;
  alert(city.options);            // HTMLOptionsCollection;
  alert(city.options[0]);          // HTMLOptionElement;
  alert(city.type);             // select-one;
  // PS:选择框里的type属性有可能是:select-one,也有可能是:select-multiple;
  // 这取决于HTML代码中有没有multiple属性;

  alert(city.options[0].text);       // 上海text,获取text值;
  alert(city.options[0].value);      // 上海value,获取value值;
  // PS:操作select时,最好使用HTMLDOM,以为浏览器兼容性比较好;
  // 如果使用标准DOM,会因为不同的浏览器导致不同的结果;
  // PS:当选项没有value值的时候,IE会返回空字符串,其他浏览器会返回text值;

2.选择选项

对于只能选择一项的选择框,使用selectedIndex属性最为简单;

复制代码 代码如下:

    addEvent(city,'change',function(){
        alert(this.selectedIndex);                        // 得到当前选项的索引,从0开始;
        alert(this.options[this.selectedIndex].text);     // 得到当前选项的text值;
        alert(this.options[this.selectedIndex].value);    // 得到当前选项的value值;
    });
    city.selectedIndex = 1;                               // 设置selectedIndex可以定位某个索引;

通过option的属性selected(布尔值),也可以设置定位某个索引,设置为true即可;
    city.options[0].selected = true;                      // 设置第一个索引;

selected和selectedIndex区别:
1.selected是返回的布尔值;所以一般用于判断上;
2.selectedIndex返回的是数值,一般用于设置和获取;

复制代码 代码如下:

    addEvent(city,'change',function(){
        if(this.options[2].selected == true){             // 判断第三个选项是否被选定;
            alert('正确!');
        }
    });

3.添加选项
// 如需要动态的添加选项,我们提供两种方案:DOM和Option构造函数;
(1).DOM
var option = document.createElement('option');
option.appendChild(document.createTextNode('北京 text'));
option.setAttribute('value','北京 value');
city.appendChild(option);

(2).Option构造函数
var option = new Option('北京 text','北京 value');
city.appendChild(option); // IE出现bug;

(3).使用add()方法来添加选项:
var option = new Option('北京 text','北京 value');
city.add(option,0); // 0,表示添加到第一位;
// PS:在DOM规定,add()中两个参数是必须的,如果不正确索引,那么第二个参数设置null即可,即默认移入最后一个选项;
// 但在IE中第二个参数是可选的,所以设置null表示放入不存在的位置,导致失踪;
// 为了兼容性,可以传递undefined即可兼容;
city.add(option,null); // IE不显示了;
city.add(option,undefined); // 兼容;

 4.移除选项

// 有三种方式可以移除某一个选项:DOM移除/remove()方法移除和null移除;
city.removeChild(city.option[0]); // DOM移除;
city.remove(0); // remove()移除,推荐;
city.options[0] = null; // null移除;
// PS:当第一项移除后,下面的项,往上移,所以不停的移除第一项,即可全部移除;

5.移动选项

// 如果有两个选择框,把第一个选择框里的第一个选项移到第二个选择框里,并且第一个选择框里的第一项被移除;
var city = fm.elements['city']; // 第一个选择框;
var info = fm.elements['info']; // 第二个选择框;
info.appendChild(city.options[0]); // 移动,并在第一个选择框中删除;

 6.排列选项

选择框提供了一个index属性,可以得到当前选项的索引值,和selectedIndex的区别是,一个是选择框对象的调用,一个是选项对象的调用;

复制代码 代码如下:

     var option1 = city.options[1];
     city.insertBefore(option1,city.options[option1.index-1]);    // 往上移位;

7.单选按钮

// 通过checked属性来获取单选按钮的值;
  for(var i=0; i<fm.sex.length; i++){          // 循环单选按钮; 
    if(fm.sex[i].checked == true){           // 遍历每一个,找出处于选中状态的那一个;
      alert(fm.sex[i].value);            // 得到值;
    }
  }
  // PS:除了checked属性之外,单选按钮还有一个defaultChecked按钮,
  // 它获取的是原本的checked按钮对象,而不会因为checked的改变而改变;
  if(fm.sex[i].defaultChecked == true){
    alert(fm.sex[i].value);
  }

8.复选按钮

// 通过checked属性来获取复选按钮的值,
  var love = '';
  for(var i=0; i<fm.love.length; i++){
    if(fm.love[i].checked == true){
      love += fm.love[i].value;
    }
  }
  alert(love);
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.