Summary of the form

The form (

) is used to collect user-submitted data and send it to the server.

A common form is the login screen, where the user submits a username and password for the server to verify.

  <form action="/handling-page" method="post">
    <div>
      <label>User name:<input type="text" id="name" name="user_name" />
      </label>
    </div>
    <div>
      <label>Password:<input type="password" id="passwd" name="user_passwd" />
      </label>
    </div>
    <div>
      <input type="submit" id="submit" name="submit_button" value="Submit" />
    </div>
  </form>
Copy the code

The code above is a simple form with three controls: a username field, a password field, and a submit button.

When the user clicks the “Submit” button, each control will generate a key-value pair. The key-name is the name property of the control, and the key-value is the value property of the control. The key-name and key-value are connected by an equal sign. For example, the name attribute of the user name input field is user_name, and the value attribute is the value entered by the user, assuming “triple”, when submitted to the server, a key value pair user_name= triple will be generated.

Form basis

The form type in JS is represented as HTMLFormElement. This type inherits from HTMLElement.

In addition to the usual methods of getting elements, such as querySelector and getElementById, you can use Document. forms to get all the form elements of a page.

<form name="myForm">
</form>
<form name="myForm2">
Copy the code

You get the form result that looks like this

So we can use the index to get the corresponding form element.

document.forms['myForm2'] // Get the form element named myForm2
docoment.form[0] // Get the first form
Copy the code

method

All key-value pairs are submitted to the server. However, the submitted data format is related to the method attribute of the

element. This property specifies the HTTP method for submitting data. If the GET method is used, all key-value pairs are submitted to the server in the form of a URL query string, such as/handlinging-page? User_name = user_passwd=123&submit_button= Submit Here is the HTTP header for the GET request.
GET /handling-page? User_name = user_passwd=123&submit_button= Submit Host: example.comCopy the code

If the post method is used, the data is sent to the server as the body of the request. All key-value pairs are joined in a row. Here is the header of the POST request.

POST/handlinging-page HTTP/1.1 Host: example.com Content-type: application/x-www-form-urlencoded content-length: 74 user_name= js&user_passwd =123&submit_button= SubmitCopy the code

But in the actual submission, as long as the key value is not the LEGAL character of the URL, such as the above Chinese character Zhang SAN and submit, then the browser will automatically encode and send to the server.

Submission methods

Use a type=submit control on the form to submit the form.

    <form>
      <input type="submit" value="Submit" />
    </form>
Copy the code

We usually use the button tag and place it directly in the form so that we can submit the form. The default type of button is submit

    <form>
      <button>submit<button>
    </form>
Copy the code

In addition, we can also use the form element’s Submit method to submit the form through JS.

document.querySelector('form').submit()
Copy the code

The Submit method comes from the HTMLFormElement object, and the instance form element is called by inheriting HTMLFormElement.

The reset method resets the value of all forms

document.querySelector('form').reset()
Copy the code

Submit form details

A button control or an input control whose type is Submit can be used to submit a form. An input control whose type is Image can also be used to submit a form.

<input type='image' src='xxx.jpg'/>
Copy the code

If the focus is on the three form controls above, pressing enter also triggers the form submission. If there is no submit button, the form will not trigger the submit button even if the enter key is pressed.

When the form is submitted in the above manner, a Submit event is triggered so that we can verify the form data. If the default behavior is blocked at this point, you can cancel the commit.

let form =document.getElementById('myform')
form.addEvemtListener('submit'.(e) = >{
  e.preventDefault()// Cancel the submission
})
Copy the code

If the submit() method is used, the form control is not required and js script is triggered directly. However, this method does not trigger the Submit event, so the form verification should be performed first before the submit method is triggered.

The user may trigger a second submission when submitting the form. It is currently a good idea to disable the form property after submission, or to listen for the onSubmit event to cancel the subsequent form submission.

Reset the form

In addition to using the reset method to reset the form, you can also use an input control with type value reset or a button control to reset the form.

<input type='reset' value='reset form'/>
<button type='reset'>reset form</button>
Copy the code

Both the reset method and the controls trigger the reset event when the form is reset. Again, we can prevent the form from being reset by disabling the default behavior

let form =document.getElementById('myform')
form.addEvemtListener('reset'.(e) = >{
  e.preventDefault()// Cancel the submission
})
Copy the code

FormData object

Form data is sent to the server as key-value pairs, which is done automatically by the browser. But sometimes, we need to do it ourselves with JS, construct a form and send it to the server. So we’re going to use the formData object

FormData is a constructor that generates an instance of the form

var formData = new FormData(form)
Copy the code

The FormData constructor takes a DOM form element as an argument, and it automatically handles the form’s key-value pairs. This parameter is optional; if omitted, it indicates an empty form.

new FormData() // An empty form
Copy the code

If you receive a form element, you can get the key-value pairs of the form element.

<form id="myForm" name="myForm">
  <div>
    <label for="username">User name:</label>
    <input type="text" id="username" name="username">
  </div>
  <div>
    <label for="useracc">Account:</label>
    <input type="text" id="useracc" name="useracc">
  </div>
  <div>
    <label for="userfile">Uploading files:</label>
    <input type="file" id="userfile" name="userfile">
  </div>
<input type="submit" value="Submit!">
</form>
Copy the code

We can use FormData to process the form above.

var myForm = document.getElementById('myForm')
var formData = new FormData(myForm)
formData.set('username'.'xxx')
formData.get('username') // xxx
for(let k of formData.keys()){
  console.log(k)
}
//"username"
//"useracc"
//"userfile"
Copy the code

FormData provides the following methods

  • Formdata. get(key) : obtains the key value corresponding to the specified key name. If there are multiple key-value pairs with the same name, return the key value of the first key-value pair.
  • Formdata.getall (key) : Returns an array representing all key values corresponding to the specified key name. If there are multiple key-value pairs with the same name, the array contains all the keys.
  • Formdata. set(key, value) : Sets the key value of the specified key name. If the key name does not exist, the pair is added; otherwise, the key for the specified key name is updated. If the second argument is a file, you can also use the third argument, which represents the file name.
  • Formdata.delete (key) : deletes a key-value pair. The parameter is the key name.
  • Formdata.append (key, value) : Adds a key-value pair. If the key name is duplicated, two key-value pairs with the same key name are generated. If the second argument is a file, you can also use the third argument, which represents the file name.
  • Formdata.has (key) : Returns a Boolean value indicating whether there is a key-value pair with the key name.
  • Formdata.keys () : Returns a traverser object used for… The of loop iterates through all the key names.
  • Formdata.values () : Returns a traverser object for… The of loop iterates through all the key values.
  • Formdata.entries () : Returns a traverser object used for… The of loop iterates through all key-value pairs. If you use for… Of loops through the FormData instance, which is called by default.
var myForm = document.getElementById('myForm')
var formData = new FormData(myForm)
formData.set('username'.'xxx')
formData.append('username'.'yyy')
console.log(formData.getAll('username')) //["xxx", "yyy"]

formData.append('userpic[]', myFileInput.files[0].'user1.jpg');
formData.append('userpic[]', myFileInput.files[1].'user2.jpg');
Copy the code

Here is an example of a traverser

var formData = new FormData();
formData.append('key1'.'value1');
formData.append('key2'.'value2');

for (var key of formData.keys()) {
  console.log(key);
}
// "key1"
// "key2"

for (var value of formData.values()) {
  console.log(value);
}
// "value1"
// "value2"

for (var pair of formData.entries()) {
  console.log(pair[0] + ':' + pair[1]);
}
// key1: value1
// key2: value2

// Equivalent to traversing formdata.entries ()
for (var pair of formData) {
  console.log(pair[0] + ':' + pair[1]);
}
// key1: value1
// key2: value2
Copy the code

Form validation

The form itself has apis that specify conditions for automatic validation.

<! -- Required --> <input required> <! - must conform to the regular expression - > < input pattern = "banana | cherry" > <! Input minlength="6" maxLength ="6"> <! - value must be between 1 to 10 - > < input type = "number" Max min = "1" = "10" > <! <input type=" Email "> <! <input type="URL">Copy the code

If a control passes validation, it matches the: VALID CSS pseudo-class, and the browser continues the form submission process. If not, the control matches the CSS pseudo-class :invalid, and the browser terminates the form submission with an error message.

input:invalid {
  border-color: red;
}
input,
input:valid {
  border-color: #ccc;
}
Copy the code

checkValidity()

This method is used to manually trigger form validation. Both form elements and form controls have the checkValidity() method.

// Triggers validation of the entire form
form.checkValidity()

// Triggers validation of a single form control
formControl.checkValidity()
Copy the code

This method returns a Boolean value, true for pass and false for failure.

function submitForm(action) {
  var form = document.getElementById('form');
  form.action = action;
  if(form.checkValidity()) { form.submit(); }}Copy the code

WillValidate properties

The willValidate property of a control element is a Boolean value indicating whether the control will be validated at commit time.

// The HTML code is as follows
// <form novalidate>
// 
// </form>

var input = document.querySelector('#name');
input.willValidate // true
Copy the code

ValidationMessag properties

The validationMessage property of the control element returns a string representing the prompt text displayed by the browser when the control does not meet the validation criteria. This property returns an empty string in two cases.

  • The control does not validate automatically on submission
  • The control meets verification conditions
// The HTML code is as follows
// <form><input type="text" required></form>
document.querySelector('form input').validationMessage
// "Please fill in this field."
Copy the code

Here’s another example

  <form id="myForm" name="myForm">
    <label for="username">User name:</label>
    <input type="text" id="username" name="username" required>
    <div id="prompt"></div>
  </form>
Copy the code
var input = document.getElementById('username')
if(! input.checkValidity()) {document.getElementById('prompt').innerHTML = input.validationMessage;
}
Copy the code

setCustomValidity()

So if we want to specify what happens after a form validation failure, we can use this API. So again, the example above, let’s modify it

var input = document.getElementById('username')
if(! input.checkValidity()) { input.setCustomValidity('I can't submit it without filling it in.')
  document.getElementById('prompt').innerHTML = input.validationMessage;
}
Copy the code

I have modified the prompt text of the system

<form action="somefile.php">
  <input
    type="text"
    name="username"
    placeholder="Username"
    pattern="[a-z] {1,}"
    id="username"
  >
  <input type="submit">
</form>
Copy the code

The form input box above requires that only lowercase letters and no more than 15 characters be entered. If the input does not meet the requirements (for example, ABC), an error message “Please match the requested format.” will be displayed on Chrome when the form is submitted. The setCustomValidity() method is used to replace the error message.

var input = document.getElementById('username');
input.oninvalid = function (event) {
  event.target.setCustomValidity(
    'User name must be lowercase, cannot be empty, and cannot exceed 15 characters.'
  );
}
Copy the code

In the above code, the setCustomValidity() method is called in the listener function for the invalid event.

This method can also be called directly, in which case if the argument is not an empty string, the browser will assume that the control did not pass verification and will immediately display an error message for this method setting.

/ * HTML code is as follows the < form > < p > < input type = "file" id = "fs" > < / p > < p > < input type = "submit" > < / p > < / form > * /

document.getElementById('fs').onchange = checkFileSize;

function checkFileSize() {
  var fs = document.getElementById('fs');
  var files = fs.files;
  if (files.length > 0) {
     if (files[0].size > 75 * 1024) {
       fs.setCustomValidity('File cannot be larger than 75KB');
       return;
     }
  }
  fs.setCustomValidity(' ');
}
Copy the code

If the file is larger than 75KB, the code will set the verification failure and give a custom error message. Then, when you click the submit button, an error message is displayed. The verification failure cannot be automatically eliminated. Therefore, if all files meet the conditions, set the error message to an empty string and manually eliminate the verification failure status.

The gnosis.xml.validity properties

The validity property of the control element returns a ValidityState object containing information about the current ValidityState.

This object has the following properties, all of which are read-only.

  • Validitystate. badInput: Boolean value indicating whether the browser failed to convert the user’s input to the correct type, such as a string entered in a value field.
  • ValidityState. CustomError: Boolean, if said is called setCustomValidity () method, which sets the calibration information to a non-empty string.
  • ValidityState. PatternMismatch: Boolean, said user input values are not meet the requirements of the model.
  • ValidityState. RangeOverflow: Boolean, indicates whether the user input value is greater than the maximum range.
  • ValidityState. RangeUnderflow: Boolean, indicates whether the user input values less than the minimum range.
  • ValidityState. StepMismatch: Boolean, said set of user input value does not conform to the step (i.e., cannot be divided exactly by step value).
  • Validitystate. tooLong: Boolean value indicating that the user entered more than the maximum number of words.
  • Validitystate. tooShort: Boolean value indicating that the user has entered less than the minimum number of characters.
  • ValidityState. TypeMismatch: Boolean, said users fill in the values do not conform to the requirements of the type (mainly type of Email or URL).
  • Validitystate. valid: Indicates a Boolean value indicating whether the user meets all verification conditions.
  • ValidityState. ValueMissing: Boolean, says the user is not fill in the required value.
var input = document.getElementById('myinput');
if (input.validity.valid) {
  console.log('Verified');
} else {
  console.log('Verification failed');
}
Copy the code
var txt = ' ';
if (document.getElementById('myInput').validity.rangeOverflow) {
  txt = 'Value exceeds upper limit';
}
document.getElementById('prompt').innerHTML = txt;
Copy the code

If you want to disable the browser from popping up an error message for form validation, you can listen for invalid events.

var input = document.getElementById('username');
var form  = document.getElementById('form');

var elem = document.createElement('div');
elem.id  = 'notify';
elem.style.display = 'none';
form.appendChild(elem);

input.addEventListener('invalid'.function (event) {
  event.preventDefault();
  if(! event.target.validity.valid) { elem.textContent ='Username must be lowercase';
    elem.className     = 'error';
    elem.style.display = 'block';
    input.className    = 'invalid animated shake'; }}); input.addEventListener('input'.function(event){
  if ( 'block' === elem.style.display ) {
    input.className = ' ';
    elem.style.display = 'none'; }});Copy the code

In the code above, event.preventDefault() prevents the browser from displaying the default validation failure message in case of an invalid event (form authentication failed), and then sets the custom error preventDefault.

The novalidate attribute of the form

Novalidate, the HTML attribute of the form element, turns off automatic validation in the browser.

<form novalidate>
</form>
Copy the code

This property can also be set in the script.

form.noValidate = true;
Copy the code

If the form element does not have a novalidate attribute set, the formNovalidate attribute of the submit button (a

<form>
  <input type="submit" value="submit" formnovalidate>
</form>
Copy the code

Enctype attribute

Forms can send data to the server in four different encodings. The encoding format is determined by the encType attribute of the form.

Suppose the form has two fields, foo and baz, where the value of foo is equal to bar and the value of baz is a two-line string.

The first line.
The second line.
Copy the code

The form can be sent to the server in any of the following four formats.

(1) GET method

The encType attribute is invalid if the form uses the GET method to send data.

<form
  action="register.php"
  method="get"
  onsubmit="AJAXSubmit(this); return false;"
>
</form>
Copy the code

The data will be emitted as a query string of the URL.

? foo=bar&baz=The%20first%20line.%0AThe%20second%20line.Copy the code

(2) application/x – WWW – form – urlencoded

If the form sends data using POST and omits the encType attribute, the data is sent in Application/X-www-form-urlencoded format (because that is the default).

<form
  action="register.php"
  method="post"
  onsubmit="AJAXSubmit(this); return false;"
>
</form>
Copy the code

The HTTP request sent is as follows.

Content-Type: application/x-www-form-urlencoded

foo=bar&baz=The+first+line.%0D%0AThe+second+line.%0D%0A
Copy the code

In the above code, the %0D%0A in the data body represents the newline character (\r\n).

(3) the text/plain

If the form uses the POST method to send data and the encType attribute is text/plain, the data will be sent in plain text.

<form
  action="register.php"
  method="post"
  enctype="text/plain"
  onsubmit="AJAXSubmit(this); return false;"
>
</form>
Copy the code

The HTTP request sent is as follows.

Content-Type: text/plain

foo=bar
baz=The first line.
The second line.
Copy the code

(4) the multipart/form – the data

If the form uses the POST method and the encType attribute is multipart/form-data, the data will be sent in a mixed format.

<form
  action="register.php"
  method="post"
  enctype="multipart/form-data"
  onsubmit="AJAXSubmit(this); return false;"
>
</form>
Copy the code

The HTTP request sent is as follows.

Content-Type: multipart/form-data; boundary=---------------------------314911788813839

-----------------------------314911788813839
Content-Disposition: form-data; name="foo"

bar
-----------------------------314911788813839
Content-Disposition: form-data; name="baz"

The first line.
The second line.

-----------------------------314911788813839--
Copy the code

This format is also used to upload files.

File upload

The user uploads the file, also through the form. The user sends a local file through the file input field, and when the form is submitted, the browser sends the file to the server.

<input type="file" id="file" name="myFile">
Copy the code

You also need to set the method attribute of the form

element to POST and the encType attribute to multipart/form-data. The encType attribute determines the content-Type field of the HTTP header. By default, this field is Application/X-www-form-urlencoded, but files are uploaded with multipart/form-data.
<form method="post" enctype="multipart/form-data">
  <div>
    <label for="file">Select a file</label>
    <input type="file" id="file" name="myFile" multiple>
  </div>
  <div>
    <input type="submit" id="submit" name="submit_button" value="Upload" />
  </div>
</form>
Copy the code

In the HTML code above, the multiple property of the File control specifies that multiple files can be selected at once. Without this property, only one file can be selected at a time.

var fileSelect = document.getElementById('file');
var files = fileSelect.files;
Copy the code

Then, create a new FormData instance object, simulate the FormData sent to the server, and add the selected file to it.

var formData = new FormData();

for (var i = 0; i < files.length; i++) {
  var file = files[i];

  // Upload only image files
  if(! file.type.match('image.*')) {
    continue;
  }

  formData.append('photos[]', file, file.name);
}
Copy the code

Finally, upload files to the server using Ajax.

var xhr = new XMLHttpRequest();

xhr.open('POST'.'handler.php'.true);

xhr.onload = function () {
  if(xhr.status ! = =200) {
    console.log('An error occurred! '); }}; xhr.send(formData);Copy the code

In addition to sending FormData instances, you can also send files directly with AJAX.

var file = document.getElementById('test-input').files[0];
var xhr = new XMLHttpRequest();

xhr.open('POST'.'myserver/uploads');
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);
Copy the code

The File object

The File object represents a File and is used to read and write File information. The most common is the upload control for forms. After the user selects a File, the browser generates an array of each File selected by the user, which is a File instance object.

// The HTML code is as follows
// <input id="fileItem" type="file">
var file = document.getElementById('fileItem').files[0];
file instanceof File // true
Copy the code

In the above code, file is the first file selected by the user, which is an instance of File.

File constructor

We can also generate File instance objects

new File(array, name [, options])
Copy the code

The File() constructor takes three arguments.

  • Array: An array whose members can be binary objects or strings representing the contents of a file.
  • Name: indicates the file name or file path.
  • Options: Configures objects and sets instance properties. This parameter is optional.

The third parameter configures the object, which can set two properties.

  • Type: a string representing the MIME type of the instance object. The default value is an empty string.
  • LastModified: timestamp indicating when the last modification was made. Default is date.now ().
var file = new File(
  ['foo'].'foo.txt',
  {
    type: 'text/plain'});Copy the code

The File object has the following instance properties.

  • File.lastModified: time when the File was lastModified
  • File.name: indicates the File name or File path
  • File.size: File size (in bytes)
  • File.type: indicates the MIME type of a File
var myFile = new File([], 'file.bin', {
  lastModified: new Date(2018.1.1)}); myFile.lastModified/ / 1517414400000
myFile.name // "file.bin"
myFile.size / / 0
myFile.type / / ""
Copy the code

File objects have no instance methods of their own, and since they inherit from Blob objects, they can use slice(), the instance method of Blob.

The FileList object

A FileList object is an array-like object that represents a list of selected files. Each member is an instance of File. It appears mainly on two occasions.

  • File control node (<input type="file">), returns a FileList instance.
  • When you drag a group of files, the datatransfer. files property in the target area returns a FileList instance.
// The HTML code is as follows
// <input id="fileItem" type="file">
var files = document.getElementById('fileItem').files;
files instanceof FileList // true
Copy the code

In the above code, the files property of the file control is a FileList instance.

The main instance property of a FileList is length, which indicates how many files are contained.

FileReader object

The FileReader object is used to read the contents of a File contained in a File object or Blob object.

Browsers natively provide a FileReader constructor that generates instances of FileReader.

var reader = new FileReader();
Copy the code

FileReader has the following instance attributes.

  • Filereader. error: Error object generated when reading a file
  • Filereader. readyState: an integer that indicates the current state of the file when it is read. There are three possible states: 0 indicates that no data has been loaded, 1 indicates that data is being loaded, and 2 indicates that loading is complete.
  • Filereader. result: The content of the file after reading, which can be a string or an ArrayBuffer instance.
  • Filereader. onabort: The listener for the abort event (the user terminates the read operation).
  • Filereader. onerror: Listener for error events (read errors).
  • Filereader. onload: a function that listens for the load event, usually with the result attribute, to fetch the file contents.
  • Filereader. onloadStart: a listener function for the loadStart event (read operation started).
  • Filereader. onloadEnd: A listener for the loadEnd event (end of read operation).
  • Filereader. onProgress: A listener for the progress event (reading operation in progress).

Here is an example of listening for a LOAD event.

<input type="file" onchange=" onchange (event)"> function onchange (event) {var file = event.target.files[0]; var reader = new FileReader(); reader.onload = function (event) { console.log(event.target.result) }; reader.readAsText(file); }Copy the code

In the above code, every time the file control changes, we try to read the first file. If the load succeeds (a load event occurs), the contents of the file are printed.

FileReader has the following instance methods.

  • Filereader.abort () : Abort the read operation, and the readyState property becomes 2.
  • FileReader. ReadAsArrayBuffer () : read in the ArrayBuffer format file, read the result after the completion of property returns a ArrayBuffer instance.
  • FileReader. ReadAsBinaryString () : read, after the completion of the result attribute will return to the original binary string.
  • Filereader.readasdataurl () : After reading, the result property returns a string in DataURL format (Base64 encoded) representing the contents of the file. For image files, this string can be used<img>SRC attribute of the element. Note that this string cannot be Base64 decoded directly, and must be prefixed with data:/; Base64 is decoded after it is removed from the string.
  • Filereader.readastext () : After reading, the result property returns a text string for the contents of the file. The first argument to this method is a Blob instance representing the file, and the second argument, optional, represents the text encoding, which defaults to UTF-8.

Here’s an example.

 

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.addEventListener('load'.function () {
    preview.src = reader.result;
  }, false);

  if(file) { reader.readAsDataURL(file); }}Copy the code

In the above code, after the user selects the image file, the script automatically reads the file’s contents and then assigns them to the SRC attribute of the element as a Data URL to display the image.

Form events

Form submissions tend to have a default refresh behavior, which we usually cancel with e.preventDefault.

The input event

The input event is emitted when the values of INPUT, SELECT, and Texttarea change. The feature is that every operation will trigger once. Continuous trigger.

<input id="ipt" type="text"/>
Copy the code
ipt.addEventListener('input'.() = >{
  console.log('Triggered an input event')})Copy the code

The above code, each time you modify text, triggers the input event and executes the callback.

<select name="" id="ipt">
  <option value="1">Option a</option>
  <option value="2">Option 2</option>
</select>
Copy the code
ipt.addEventListener('input'.() = >{
  console.log('Triggered an input event')})Copy the code

In the same way as the select tag above, each time a different option is selected, the input event is also triggered. Input is a large form event that contains a lot of content and typically occurs immediately after the change.

The React onChange event is not a native change event, especially on controlled components. Fires every time the value changes. Vue’s change event is just like a native event.

So to summarize the differences between input and change native events:

  • Input is triggered (continuously) every time a value changes
  • Change is triggered when you lose focus, although the value may have changed multiple times.

The select event

Select is the selected text event, which is triggered when text is selected in the input and can be retrieved via the value property in e.target

<input id="ipt" type="text">
Copy the code
ipt.addEventListener('select'.(e) = >{
  console.dir(e.target.value)
})
Copy the code

The code above prints the selected text directly.

The selected text is available through the selectionDirection, selectionEnd, selectionStart, and Value attributes of the Event. target element.

Change event

We already know the nature of the input event above. Although the input event is good, sometimes too frequent firing mechanism is not suitable, so we need to use the change event, which is the nature of the value is changed before firing.

For the SELECT tag, the change event is basically the same as input, but input has obvious special features, such as

<input id="ipt" type="text">
Copy the code
ipt.addEventListener('change'.() = >{
  console.log('Triggered the change event')})Copy the code

This event is emitted only if the value has changed and lost focus.

The change event is emitted when the , < SELECT >, and

  • Triggered when a radio or checkbox is activated.
  • Triggered when the user submits. For example, do the selection from the following list (SELECT), and do the selection in the date or file input field.
  • When the text box or<textarea>Emitted when the value of the element changes and the focus is lost.
// The HTML code is as follows
// 
// 
// 
// 
// </select>

function changeEventHandler(event) {
  console.log(event.target.value);
}
Copy the code

If you compare the input event example above, you’ll see that the input and change events are basically equivalent for < SELECT > elements.

Invalid event

When the form is submitted, an invalid event is emitted if the form’s values do not meet the criteria.

<form>
  <input type="text" required oninvalid="console.log('invalid input')" />
  <button type="submit">submit</button>
</form>
Copy the code

In the above code, because the form is mandatory, an invalid event is triggered when the user clicks Submit without completing it

Reset event

The reset event is emitted when the form resets (all form members return to their default values).

The submit event

The Submit event is triggered when form data is submitted to the server. Note that the Submit event occurs on the

element, not the

InputEvent Event object

The InputEvent interface is used to describe instances of input events. This interface inherits the Event interface and defines some of its own instance properties and instance methods.

Browsers natively provide the InputEvent() constructor, which is used to generate instance objects.

new InputEvent(type, options)
Copy the code

The first argument, a string representing the event name, is required. The second parameter is an optional configuration object that sets the properties of the event instance. In addition to the configuration properties of the Event constructor, you can optionally set the following fields.

e.data

This interface returns the changed content.

<input type="text" id="ipt">
Copy the code
ipt.addEventListener('input'.(e) = >{
  console.log(e.data)
})
Copy the code

The code above returns the changed text content, for example, entering a 1 in the text box prints a 1, entering a 2 again prints a 2, and deleting it returns NULL

e.inputType

This interface is used for input types, including the following:

  • Insert text manuallyinsertText
  • Paste insert textinsertFromPaste
  • Back to deletedeleteContentBackward
  • Forward to deletedeleteContentForward

e.dataTransfer

The inputevent. dataTransfer property returns a dataTransfer instance. This property is only valid if the text box accepts paste content (insertFromPaste) or drag content (insertFromDrop).