laitimes

Section 63 Form Forms - JavaScript for Web Front-End Development - Wang Wei

author:Zero point programmer

This content is the courseware of "Javascript Video for Web Front-end Development", please cooperate with the "Javascript" video course of Master Brother.

In HTML, forms are represented by <form > elements, which have an important place in client-side programming with a wide variety of other form input elements, such as < input>, < select>>, and <button.

The role of the form is to collect the user's input through the form elements, and then submit these input data to the server, the server processes the received data and generates a new HTML page to display on the client; in the past, the form submitted data, the server returned the data, at this time the client and the server did not have other interaction behavior, therefore, the data submission interactivity is poor, the server is heavy.

One of the first applications of Javascript is to share the task of the server processing the form, breaking the situation of relying on the server everywhere; although the Web and Javascript have made great progress, the changes in web forms are not obvious; especially some common forms, web forms do not provide a particularly good solution; the most common operation is to use Javascript to enhance the default behavior of some standard form controls.

Forms and their controls are HTML elements, you can use standard DOM technology to manipulate them, in addition to the form has been scripted, there are also specialized APIs, so in form programming, it is best to use the form API;

To get a Form form object:

The way to obtain < form > element references: the most common way is to think of it as the same as other elements, using standard DOM techniques such as getElementById() or getELementsByTagName();

All the forms in the page can be obtained through the document.forms collection, and in this HTMLCollection collection, a specific form can be obtained by numeric index or name or id value:

In older browsers or those that support backward compatibility, each form with the name attribute set will be saved as a property in the document object, such as:

Note: This method is not recommended;

Note: It is possible to specify both the id and name properties for the form, but they can be set to different values;

Form properties and methods:

Forms <form> have attributes such as action, encoding, method, and target in HTML, and in Javascript, it is the HTMLFormElement type, inheriting HTMLElement, and thus having the same default attributes as other HTML elements, but also having its own unique attributes and methods, most of which correspond to their attributes in HTML. These properties can control how the form submits data and how it is displayed, such as:

acceptCharset: A character set that the server can handle, equivalent to the access-charset feature in HTML;

action: The URL that accepts the request, equivalent to the action attribute of HTML;

elements: A collection of all controls in the form (HTMLCollection);

enctype: The encoding type (method) of the request, equivalent to the enctype attribute in HTML;

encoding: encoding, equivalent to HTML's encoding feature, is not needed;

length: read-only, the number of controls in the form;

method: The request type (method), equivalent to the HTML method attribute;

name: the name of the form, equivalent to the name attribute of HTML;

target: The name of the window used to send requests and receive responses, equivalent to HTML targets

reset(): Method to reset all form fields to default values;

submit(): method, submit form;

Most of the above properties are writable;

You can also use DOM methods to create forms dynamically, such as:

Submit submission form:

Using the < input > the type attribute is "submit" or "image" to submit the form, or <button > can also submit the form;

The above button, as long as any form element has the focus, press Enter to submit the form; if there is no submit button in the form, pressing the Enter key will not submit the form, but there is a special case, if there is only one text box, even if there is no submit button, enter will be submitted;

Note: textarea is an exception, if entering in the text area will wrap instead of submitting the form;

When a form is submitted in this way, the browser triggers the onSubmit event before sending the request to the server, which allows the form data to be validated to decide whether to allow the form to be submitted; the default behavior of the event is blocked or the false is returned to cancel the form submission, or if it is not blocked, the form is submitted;

If it is a DOM0-level event handler, it can also be return false;

If it is an HTML event handler, it can be return false;

Submit() method:

In Javascript, calling the submit() method also submits the form; moreover, this method does not require the form to contain a submit button, and the form can be submitted normally at any time;

The onSubmit event is not triggered when the submit() method is called to submit the form, so the form data is validated before this method is called;

Also, calling this method does not trigger constraint validation, such as:

<p> enter an integer between 1-10: < input type="number" min="1" max="10" required /></p>

Therefore, it is also necessary to validate the constraint before calling the submit() method, such as:

There is a misconception that if you add an onSubmit event to a submit button, it is invalid, it will be submitted directly, such as:

If you add an onClick event to a submit button, you can perform form submission verification, and also trigger the form's onSubmit event, for example, add the onClick event handler of the above example to the subload submit button, it can be seen that the onClick event is triggered before the form's onSubmit event;

Also, do not set the value of name or id to submit for a form element, because it will override the form's submit method, so when run, it will prompt for a submit() function that does not exist;

Also, not only the Submit button or normal button that calls the submit() method can submit the form, or even a hyperlink called the submit() method can also be submitted, but be aware that the default behavior of hyperlinks needs to be removed:

example:

There is also an important way to submit, that is, Ajax submission, that is, the use of XMLHttpRequest object for asynchronous data submission, its biggest feature is that it will not commit the entire page, only local submission.

Autocommit and prevent autocommit:

Enter, call the click() method of the submit button, call the submit() method of the form (can be in the onLoad event, and even use setTimeout to submit regularly), etc.;

If there is a submit button in the form, you can add onsubmit="return false" to the form; however, the submit button will also be invalidated;

If there is no submit button in the form, it will not be submitted automatically;

If there is only one text box in the form, but there is no submit button, the carriage return is automatically submitted, and you can add onsubmit="return false" to the form, which will not be automatically submitted; or add a hidden text box, such as:

Nor will it be automatically committed, note that the domain is not hidden;

Or listen for the onKeydown event of the text box, if it is a carriage return, do not process, such as:

If there is a submit button in the form, if any of the controls of the form are in focus, a direct carriage return can submit the form, if there is no control in the focus state, you can listen to the keydown event of the document to determine whether to press the enter key and then submit, such as:

To prevent duplicate commits:

The biggest problem that can occur when submitting a form is the repeated submission of the form; there are two ways to solve this problem: disable the submit button after the first submission of the form, or cancel subsequent form submission operations using the onSubmit event handler;

To disable the submit button:

Note: This function cannot be implemented through the onclick event handler because there is a "jet lag" between different browsers: some will trigger the onClick event before the onSubmit event of the form is triggered, and some will be opposite; for the onClick event first, it means that the button will be disabled before the submission occurs, and the result will never be submitted to the form, so it is best to use the onSubmit event to disable the submit button;

This method is not suitable for cases where the form does not contain a submit button;

To reset a form:

The form can be reset using two buttons > < input > with type attributes as reset, or <button:

When the reset button is clicked, the onReset event is triggered; this event allows you to cancel the reset operation if necessary; unreleaving is the default behavior that prevents the reset, such as:

Returning false in an HTML event handler or an onReset event at DOM0 level also cancels the default behavior;

It is also possible to call the Reset() method reset using Javascript, but unlike calling the subnet() method, which triggers the onReset event;

From a user experience perspective, resetting a form is not common, so it is possible that a form reset event was triggered unexpectedly, so this need is rare, and it is more common to provide a cancel button that allows the user to return to the previous page;

Form elements (controls):

Form controls can be accessed using native DOM methods as you would other elements in a page;

Form forms have the lackth attribute, which returns the number of form elements, but does not contain <input> elements type as "image" elements; so elements can also be accessed by accessing the form's index or properties, such as form[0] to get the first form control or form["color"] or form.color to get the first named control;

It belongs to the HTMLFormControlsCollection collection type, inherited from THE HTMLCollection; this type has no special properties or methods;

Note that the elements collection does not include an input element with type equal to image;

All elements can be accessed through the form elements collection index or the name attribute, such as:

This approach is consistent with accessing form elements directly using the form's index or name attributes, in contrast, and is still recommended because the former may not be supported in the future and will cause some ambiguity;

For example, the values of all form elements cannot be empty, such as:

If multiple form controls use the same name, a NodeList named after that name is returned via elements["name"), while only the first element is returned via elements[index].;

Therefore, the results may be different when using the index and the name attribute; in general, the id attribute is preferred, but the name attribute has a special purpose in HTML form submission, generally applied to the relevant check button group and the mutually exclusive radio button group that forces the sharing of the name attribute value; in addition, for other form elements, the purpose of setting the name attribute is to submit to the server, and the server obtains the value of the form element according to the name attribute;

Common form control properties:

With the exception of < fieldset> elements, all form controls have the same set of properties; because < input> type can represent multiple form elements, some properties apply only to some form elements, but there are also some properties that are common to all form elements:

disabled: A Boolean value that indicates whether the current control is disabled;

form: Read-only, a pointer to the form to which the current control belongs; if the form element is not contained in a <form >, the value is null;

name: read-only, the name of the current control;

readOnly: A Boolean value that indicates whether the current control is read-only;

tabIndex: Indicates the toggle (tab) ordinal of the current control;

type: The type of the current control, such as checkbox, radio, etc.;

value: read/write, the value of the form element, that is, the value that will be submitted to the server, for file, is read-only, containing the path of the file in the computer;

In addition to the form property, the above can be dynamically modified by Javascript, such as:

type attribute:

All form elements have a type attribute except < fieldset >; for < input> elements, this value is equal to the HTML attribute type value, such as: text, password, radio, checkbox, button, file, hidden, reset, submit; for other elements, the value is as follows:

File domain: <textarea> value istextarea

Single list: < select>... </select> Value is: select-one

Multi-select list: < select multiple>: </select> value is: select-multiple

Custom buttons: <button>... </button> value is: submit

Custom non-submit button: <button type="button" >: </button> value is button

Custom reset button: <button type="reset" >: </button> value is reset

Custom submit button: <button type="submit" >: </button> value is submit

In addition, the type attributes of < input > and <button > can be modified dynamically, while the type attributes of < select > elements are read-only; example: clear and dark text for password boxes:

Example: Submit a form in a pop-up window

Common form control methods:

Each form element has two methods: focus() and blur(); where the focus() method is used to get the focus, that is, to activate the form element so that it can respond to keyboard events such as:

By default, only form elements can get focus; for other elements, you can set their tabIndex to -1 and then call the focus() method, or you can get these elements to focus;

HTML5 adds an autofocus property to form controls, in browsers that support this property, as long as this property is set, you can automatically shift the focus to the corresponding control without Javascript, such as:

If this attribute is already set for an element in HTML, there is no need to call focus() in Javascript, so it is necessary to check whether the property is set before calling focus(), such as:

blur() method: removes the focus from the element;

The opposite of the focus() method is the blur() method, which removes the focus from the element; when blur() is called, it does not shift the focus to a particular element, it simply removes the focus from the element that calls the method, such as:

Common form element events:

In addition to general events such as mouse, keyboard, or other HTML when users interact with form elements, form elements support the following 3 events:

blur: triggers when the focus is lost;

focus: Triggered when focus is gained;

change: for < input> and <textarea> elements, triggered when they lose focus and the value value changes; for < select > elements, triggered when their options change;

as:

It should be emphasized that the change event is triggered for elements <input> and <textarea > when they lose focus and the value value changes; for < select > elements, it fires when its options change, such as:

When the option is changed, the change event is triggered, but at this time, the < select > is still in focus, and when it loses focus, the blur event is triggered, which is very different from the < input >;

This in the event handler:

This in the event handler is a reference to the element that triggers the event; for example, a reference to the Form object in which it resides can be obtained through this.form; other form elements in the form can be obtained through this.form.x;

Section 63 Form Forms - JavaScript for Web Front-End Development - Wang Wei

Read on