Home  >  Article  >  Web Front-end  >  Detailed introduction to forms in JavaScript

Detailed introduction to forms in JavaScript

黄舟
黄舟Original
2017-08-13 10:30:342125browse

JavaScript Form

The main purpose of this article is to introduce form-related knowledge, such as basic knowledge of forms, related usage of text box scripts, related usage of select box scripts, and other knowledge. Although in modern web development, form default behavior is rarely used to submit form data. Instead, the default behavior is disabled, and then Ajax is used to asynchronously submit form data through a POST request. But this does not mean that forms are not important anymore. Forms are still the fastest way to submit forms because JavaScript provides many properties and methods that allow us to quickly obtain the values ​​of form fields. Therefore, it is still necessary to understand and master the form.

Directory: JavaScript form

  • form form

    • Attributes

    • Method

    • Event

  • form form fields (form fields include input, button, select, textarea, the following attributes method events Common to all form fields)

    • Properties

    • Method

    • Event

  • Text box (input, textarea)

    • ##Select text

    • Filter Enter

    • Automatically switch focus

    • Properties

    • Actual application

  • Select box (select, option)

form form

Getting the Form tag in HTML can be obtained through the id, class, and name attributes , or get it directly through the form tag. Of course, you can also use

document.forms to get all form elements in HTML, and a NodeList object will be returned.

Attributes
Say an important

elements:

document.forms[0].elements Returns an array-like object, including all items under the form Form fields. It can be accessed through the name attribute or index of the form field.

let form = document.forms[0]
form.element[0] === form.element['index-0']

Method
The methods on the form include submit and reset methods. In modern web development, the default behavior is to prevent form submission. When there are no parameters, the values ​​of all form fields can be submitted to the server without clicking the button. Typically, there are three types of buttons that can submit form data.

<input type="submit" value=&#39;提交&#39; />
<button type=&#39;submit&#39;>提交</button>
<input type="image" src=&#39;pic.png&#39; />

Event
submit: When binding the submit event to the form, clicking the image button or the button of type submit will submit the form data. At this time, the default behavior of global submission of the form can be prevented through the event object. When submitting a form, in order to avoid the problem of multiple submissions caused by multiple clicks by the user, you can disable the submit button after submission.

form form fields

Attributes
are relatively simple, as follows:

  • name

  • value

  • form: Points to the current form element, read-only.

  • type

  • readOnly

  • ##disabled
  • autofocus: Automatically gain focus. HTML5 new attributes.
  • 6b3d0aed2988a64f0341f01b7609b8c3

    . Browsers that support this event include IE10+, Chrome, and Firefox. Therefore, autofocus of supported browsers will return true, and if it is not supported, it will return an empty string.

  • Method
focus(), blur(): usually used in conjunction with the blur method. For example, after the DOMContentLoaded event, let an input element gain focus so that the user can input directly.
document.addEventLitener(&#39;DOMContentLoaded&#39;, e => {
    let input = docuemnt.querySelector(&#39;.input-1&#39;)
    input.focus()
}, false)

Event

focus, blur event: In actual business, focus and blur events can be used in combination. If the input node gets focus, change the color of the input element. Reset the background color when focus is lost.
let input = document.querySelector(&#39;.input-0&#39;)
input.addEventListener(&#39;focus&#39;, e => {
    e.target.style.backgroundColor = &#39;#ccc&#39;
}, false)
input.addEventListener(&#39;blur&#39;, e => {
    e.target.style.backgroundColor = &#39;#fff&#39;
}, false)

Change event: For input and textarea elements, the change event is triggered when they change from gaining focus to losing focus and the value changes. For the select element, the change event will be triggered whenever the value changes. In other words, the change event will be triggered without losing focus. This detail needs attention.

Text box (input, textarea)

In addition to the common properties and methods of the above form fields, the text box has some of its own properties and some methods of operating text.

Properties

    maxlength: Maximum input length
  • size: The number of characters that can be displayed in the text box
  • cols: textarea column number
  • rows: textarea row number
  • ········ Below They are all new constraint validation APIs in HTML5······
  • reqiured: Required option.
  • type
    • email: Default verification
    • url: url pattern
    • number: Only numbers can be entered
    #pattern: It is actually using regular expressions in HTML. Supported by IE10+ and above browsers.
  • checkValidity method: Bind this method on document.forms[0] to check whether the entire form field is valid. If valid, returns true. Otherwise return false.
  • // type为number时,可以指定min,max,step(表示某个值得倍数)属性
    <input type="number" min=&#39;0&#39; max=&#39;100&#39; step=&#39;5&#39; name=&#39;count&#39;>
    // 此时正则默认添加了^, $,即以下正则等于&#39;^\d+$&#39;
    <input type=&#39;text&#39; pattern=&#39;\d+&#39;>
实际应用

选择文本

1.select方法:input和textarea元素都支持selct方法。这个方法不接受任何参数,表示选择某个文本框元素的所有文本

// 当input元素获得焦点是选择文本
let input = document.querySelector(&#39;.input-1&#39;)
input.addEventListener(&#39;focus&#39;, e => {
    e.target.select()
}, false)

2.setSelectionRange方法:这个方法用于选择部分文本内容。接受两个参数,起始位置和结束位置。HTML5新增的方法。IE9+以上浏览器支持。

// 当input获得焦点时,选择文本中的第二个值
let input = document.querySelector(&#39;.input-1&#39;)
input.addEventListener(&#39;focus&#39;, e => {
  let target = e.target
  console.log(target.setSelectionRange(1, 2))
}, false)

3.select事件:当文本框元素中的文本被选中时,就会触发select事件。只要选中文本就会触发,不需要全选。

4.selectionStart, selectionEnd属性:这两个属性用于或者用户选中的文本内容。因此,可以与select事件结合使用,获取用户选中的文本内容。HTML5新增的两个属性。IE9+以上浏览器支持。

let input = document.querySelector(&#39;.input-1&#39;)
input.addEventListener(&#39;select&#39;, e => {
    let target = e.target
    let start = target.selectionStart
    let end = target.selectionEnd
    console.log(target.value.slice(start, end))
}, false)

过滤输入

文本框的过滤输入主要是某些文本的输入是有条件的。比如说需要input元素中只允许输入数字。这时候就需要用到文本的过滤。基本思路如下

1.通过监听keypress事件,判断输入时的字符是否是数字。通过charCode判断。keypress事件会在用户按下键盘上的【字符键】时触发。

2.如果不是,则取消默认行为,即取消文本的输入。

let input = document.querySelector(&#39;.input-1&#39;)
input.addEventListener(&#39;keypress&#39;, e => {
  let charCode = e.charCode
  if (!/[\d+.+-]/g.test(String.fromCharCode(charCode))) {
    e.preventDefault()
  }
}, false)

此方法通过charCode属性来判断用户输入的字符是否是数字字符,如果是则可以输入,如果不是则禁止输入。这里要注意的是,不能通过input的value属性来判断。因为keydown和keypress事件会在value改变之前触发,而keyup事件则是在value发生改变之后触发。因此,keypress获取value值是上一次的值,但是keypress事件可以获取到按下键盘时的charCode属性,然后通过String对象的fromCharCode转成对应的字符,根据此字符做一次正则验证即可。同时,charCode属性只有在keypress事件才存在,在keydown和keyup事件中都会返回0。

自动切换焦点

这种应用主要用于手机号码上。如手机号码可以分为'334'的结构。因此可以创建三个input,当输入完毕时自动切换焦点到下一个input上。

// 必须设置最大值
<input type="text" name=&#39;text1&#39; maxlength="3">
<input type="text" name=&#39;text2&#39; maxlength="3">
<input type="text" name=&#39;text3&#39; maxlength="4">
// 当value的length等于maxleng时,发生跳转
function judge (len, max, target, form) {
  if (len === max) {
    let length = form.elements.length
    for (let i = 0; i < length; i++) {
      if (target === form.elements[i]) {
        if (form.elements[i + 1]) {
          form.elements[i + 1].focus()
        }
      }
    }
  }
}
// 给三个input绑定keyup事件,通过事件代理方式。
document.addEventListener(&#39;keyup&#39;, e => {
  let target = e.target
  let form = target.form
  let len = target.value.length
  let maxLen = target.maxLength
  switch (target.name) {
    case &#39;text1&#39;:
      judge(len, maxLen, target, form)
      break
    case &#39;text2&#39;:
      judge(len, maxLen, target, form)
      break
    case &#39;text3&#39;:
      judge(len, maxLen, target, form)
      break
  }
}, false)

选择框(select, option)

选择框是通过select和option元素组合而成的。除了表单字段共有的属性和方法之外,在这两个元素上提供了其他的属性和方法。目的是为了更加方便的操作选择框元素。

select元素
  • add(newOption, targetOption):在select元素上有add方法,向select元素插入新的option元素。传入两个参数:新的option元素和目标option元素。

  • multiple属性: 是否允许多项选择。如果未添加此属性,则select元素的type属性为'select-one'。否则为'select-multiple'。

  • options属性:取得该select元素下的所有options元素。返回一个类数组对象。

  • selectedIndex属性: 选中options元素的索引值。

  • size属性: 可见的行数

  • value属性: 发送到服务器的值,如果没有这个属性,则会取innerText的值。

option元素
  • index: 索引值

  • label: 当前选项的标签

  • selected: 被选中的option元素

  • text: 文本

  • value: 发送到服务器的值

The above is the detailed content of Detailed introduction to forms in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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