Form basis

Web forms are in HTML as

  • Action: The requested URL, equivalent to the HTML action property.
  • Elements: HTMLCollection of all controls in the form.
  • Enctype: The encoding type of the request, equivalent to the HTML encType attribute.
  • Length: Number of controls in the form.
  • Method: The method type of an HTTP request, usually “get” or “POST”, equivalent to the HTML method attribute.
  • Name: The name of the form, equivalent to the HTML name attribute.
  • Reset () : Resets form fields to their default values.
  • Submit () : Submits the form.
  • Target: The name of the window used to send the request and receive the response, equivalent to the TARGET attribute in HTML.

There are several ways to get a reference to an element. The most common is to assign an ID attribute to a form as if it were a normal element, so you can use getElementById() to get the form, for example:

let form = document.getElementById("form1");
Copy the code

In addition, you can use the Document.Forms collection to get all the form elements on the page. You can then further access a particular form using a numeric index or the form’s name. Such as:

// Get the first form on the page
let firstForm = document.forms[0];
// Get the form named "form2"
let myForm = document.forms["form2"];
Copy the code

Older browsers, or those that are strictly backward compatible, also treat the name of each form as an attribute of the Document object. For example, a form named “form2” can be accessed through document.form2. This approach is not recommended because it is error-prone and the properties may be removed by the browser in the future.

Note that a form can have both an ID and a name, and they can be different.

Submit the form

Forms are submitted by the user clicking either a submit button or an image button. Submit buttons can be defined using an or element whose Type attribute is “submit”, and image buttons can be defined using an element whose type attribute is “image”. Click on all the buttons defined in the following example to submit their form:

<! -- Universal Submit button -->
<input type="submit" value="Submit Form">
<! -- Customize submit button -->
<button type="submit">Submit Form</button>
<! -- Image button -->
<input type="image" src="graphic.gif">
Copy the code

If the form has any of the above buttons and the focus is on a control in the form, press Enter to submit the form as well. (The exception is the Textarea control, which wraps lines when the focus is on it.) Note that forms without a submit button are not submitted when the Enter key is pressed.

Submitting the form in this way triggers the Submit event before sending the request to the server. This provides an opportunity to validate the form data and decide whether or not to submit based on the validation results. The default behavior to prevent this event is to cancel submitting the form. For example, the following code blocks form submission:

let form = document.getElementById("myForm");
form.addEventListener("submit".(event) = > {
    // Block form submission
    event.preventDefault();
});
Copy the code

Call the preventDefault() method to prevent form submission. This is usually done when the form data is invalid and should not be sent to the server.

Of course, you can also submit the form programmatically by calling the submit() method in JavaScript. This method can be called at any time to submit the form, and the absence of a submit button does not affect the form submission. Here’s an example:

let form = document.getElementById("myForm");
// Submit the form
form.submit();
Copy the code

When a form is submitted through Submit (), the Submit event does not fire. So data validation is done before calling this method.

One of the biggest problems with form submission is that it is possible to submit the form twice. If nothing happens after submitting the form, impatient users may hit the submit button more than once. The results can be annoying (because the server handles duplicate requests) and can even be costly (if the user is shopping, they may order multiple times). There are two main ways to solve this problem: disable the submit button after the form is submitted, or cancel the subsequent form submission through the onSubmit event handler.

Reset the form

The user clicks the reset button to reset the form. The reset button can use or with the type attribute “reset”

<! Universal reset button -->
<input type="reset" value="Reset Form">
<! -- Custom reset button -->
<button type="reset">Reset Form</button>
Copy the code

Both buttons reset the form. When the form is reset, all the form fields are reset back to the values they had when the page was first rendered. If the field was empty, it becomes empty; If the field has a default value, it is restored to the default value.

The reset event is triggered when the user clicks the reset button to reset the form. This event provides an opportunity to cancel the reset. For example, the following code demonstrates how to prevent a form from being reset:

let form = document.getElementById("myForm");
form.addEventListener("reset".(event) = > {
    event.preventDefault();
});
Copy the code

Like form submission, resetting a form can be done by calling the reset() method in JavaScript, as shown in the following example:

let form = document.getElementById("myForm");
// Reset the form
form.reset();
Copy the code

Unlike the submit() method, calling the reset() method triggers the reset event as if the reset button had been clicked.

Note that resetting forms is usually discouraged in form design, as resetting forms can often be disorienting and annoying if accidentally triggered. In practice, there is little need to reset forms. In general, it is more intuitive to provide a cancel button that the user clicks to return to the previous page rather than restore all the values in the form.

Form fields

Form elements can be accessed using native DOM methods just like any other element on the page. In addition, all form elements are a value contained in the form Elements attribute (collection of elements). The Elements collection is an ordered list of references to all fields in the form, including all,,, and elements. Each field in the Elements collection is stored in the order in which they appear in the HTML tag and can be accessed through the index location and name attributes. Here are a few examples:

let form = document.getElementById("form1");
// Get the first field in the form
let field1 = form.elements[0];
// Get the field named "textBox1" in the form
let field2 = form.elements["textbox1"];
// Get the number of fields
let fieldCount = form.elements.length;
Copy the code

If multiple form controls use the same name, such as a radio button, an HTMLCollection containing all elements of the same name is returned. For example, look at the following HTML snippet:

<form method="post" id="myForm">
    <ul>
        <li><input type="radio" name="color" value="red">Red</li>
        <li><input type="radio" name="color" value="green">Green</li>
        <li><input type="radio" name="color" value="blue">Blue</li>
    </ul>
</form>
Copy the code

The HTML form has three radio buttons whose name is “color”, which ties them together. Upon accessing Elements [“color”], the returned NodeList contains these three elements. When elements[0] is accessed, only the first element is returned. Such as:

let form = document.getElementById("myForm");
let colorFields = form.elements["color"];
console.log(colorFields.length); / / 3
let firstColorField = colorFields[0];
let firstFormField = form.elements[0];
console.log(firstColorField === firstFormField); // true
Copy the code

The code above shows that the first field of the form obtained with form.elements[0] is the first element contained in form.elements[“color”].

Note that you can also access form fields through form attributes, such as form[0], which uses the index, and form[“color”], which uses the field name. Accessing these attributes is the same as accessing the form.Elements collection. This approach is provided for backward compatibility with older browsers, and actual development should use Elements.

Public properties of form fields

In addition to

  • Disabled: A Boolean value that indicates whether a form field is disabled.
  • Form: Pointer to the form to which the form field belongs. This property is read-only.
  • Name: string, the name of this field.
  • ReadOnly: Boolean value indicating whether this field is read-only.
  • TabIndex: Indicates the order in which this field is toggled when the Tab key is pressed.
  • Type: indicates the field type, such as “checkbox” and “radio”.
  • Value: Field value to be submitted to the server. For the file input field, this property is read-only and contains only the path to a file on the computer.

JavaScript can dynamically modify any property except the form property. Consider the following example:

let form = document.getElementById("myForm");
let field = form.elements[0];
// Change the value of the field
field.value = "Another value";
// Check the form to which the field belongs
console.log(field.form === form); // true 
// Set the focus for the field
field.focus();
// Disable fields
field.disabled = true;
// Change the field type (not recommended, but possible for )
field.type = "checkbox";
Copy the code

This ability to dynamically modify form field attributes makes it easy to modify the form in any way at any time. For example, a common problem with Web forms is that users often click the submit button twice. This is a serious problem where credit card charges are involved and can lead to repeated charges. A common solution to this is to disable the submit button after the first click. You can do this by listening for the Submit event. Take this example:

// Avoid submitting the form multiple times
let form = document.getElementById("myForm");
form.addEventListener("submit".(event) = > {
    let target = event.target;
    // Get the submit button
    let btn = target.elements["submit-btn"];
    // Disable the submit button
    btn.disabled = true;
});
Copy the code

The above code registers an event handler on the Form’s Submit event. When the Submit event is triggered, the code takes the submit button and sets its Disabled property to true. Note that this can’t be done by adding an onclick event handler directly to the submit button, because different browsers fire the event at different times. Some browsers fire the click event for the submit button before the form’s Submit event, while others fire the click event after. For browsers that trigger the Click event first, the button is disabled before the form is submitted, which means the form is never submitted. Therefore, it is best to disable the submit button using the Form’s Submit event. However, this approach does not work for form submission without the use of a submit button. As mentioned earlier, only the submit button can trigger the Submit event.

The type attribute can be used to divide

describe The sample HTML The value of the type
Radio list . “select-one”
Multi-select list . “select-multiple”
Custom button <button>…… </button> “submit”
Custom non-submit buttons <button type=”button”>… </button> “button”
Custom reset button <button type=”reset”>… </button> “reset”
Custom submit buttons <button type=”submit”>… </button> “submit

For and

HTML5 adds an autofocus attribute to form fields, and supported browsers automatically set focus for elements with this attribute, without the need for JavaScript. Such as:

< input type = "text"
autofocus >
Copy the code

In order for the previous code to work with Autofocus, you must first check if the attribute is set on the element. If autofocus is set, focus() is no longer called:

window.addEventListener("load".(event) = > {
    let element = document.forms[0].elements[0];
    if(element.autofocus ! = =true) {
        element.focus();
        console.log("JS focus"); }});Copy the code

Most modern browsers support the Autofocus attribute

The reverse of focus() is blur(), which removes focus from elements. Blur () is now rarely called in useful cases, so don’t do it if you don’t have to;

Public events for form fields

In addition to mouse, keyboard, changes, and HTML events, all fields support the following three events.

  • Blur: Triggered when a field loses focus.
  • Change:Fired when the value of the and element changes and loses focus, or when the selected item in the element changes.
  • Focus: Triggered when the field gains focus.

Blur and focus events are triggered when the user manually changes the field focus or calls the blur() or focus() methods. These two events apply equally to all forms.

This is not the case with the change event, which fires at different times depending on the control.

  • forAnd elements, the change event is emitted when the field loses focus and the value controller changes after it gains focus.
  • For elements, the change event is emitted when the user changes the selection, without requiring the control to lose focus. Purpose: Focus and blur events are often used to change the user interface in some way to provide visible prompts or additional features (such as displaying drop-down menus under text boxes). The change event is typically used to validate what the user has entered into a field. For example, some text boxes may be limited to receiving numeric values. For example, some text boxes may be limited to receiving numeric values. The focus event can be used to change the background color of the control to make it more clear that the current field is in focus. The blur event can be used to remove the background color. The change event can be used to change the background to red if the user enters a non-numeric value. Let textBox = document.forms[0]. Elements [0]; textbox.addEventListener(“focus”, (event) => { console.log(‘focus’) let target = event.target; if (target.style.backgroundColor ! = “red”) { target.style.backgroundColor = “yellow”; }}); textbox.addEventListener(“blur”, (event) => { console.log(‘blur’) let target = event.target; target.style.backgroundColor = /[^\d]/.test(target.value) ? “red” : “”; }); textbox.addEventListener(“change”, (event) => { console.log(‘change’) let target = event.target; target.style.backgroundColor = /[^\d]/.test(target.value) ? “red” : “”; }); The onfocus event handler here changes the background of the text box to yellow to make it more clear that it is the current active field. The onblur and onchange event handlers change the background to red when non-numeric characters are found. To test for non-numeric characters, a simple regular expression is used to detect the value of a text box. This feature must be implemented on both the Onblur and onchange event handlers to ensure that validation can be performed regardless of whether the text box changes. Note that the relationship between blur and change events is not clearly defined. In some browsers, the blur event is triggered before the change event; In other browsers, the firing order is reversed. Therefore, you cannot rely on the order in which these two events are triggered, and you must be careful when distinguishing between them. Textbox programming There are two ways to represent text boxes in HTML: single-lineElement, use element more often.

    For example, to create a text box that can display 25 characters at a time, but can display up to 50 characters at a time, you can write:

    <input type="text" size="25" maxlength="50" value="initial value">
    Copy the code

    Textarea, for example:

    < textarea rows = "25"
    cols = "5" > initial value < /textarea>
    Copy the code

    In addition to the differences in tags, both types of text boxes hold their own content in the value property. With this property, you can read and set the value of text mode, as follows:

    let textbox = document.forms[0].elements["textbox1"];
    console.log(textbox.value);
    textbox.value = "Some new value";
    Copy the code

    Select text

    Both text boxes support a method called SELECT (), which is used to select all of the text in the text box.

    Here’s an example:

    let textbox = document.forms[0].elements["textbox1"];
    textbox.select();
    Copy the code

    Function:

    • Common copy and paste functions
    • Give users the ability to delete all default content at once

    The select event

    Triggering conditions:

    • 1. The user selects the text
    • 2, the select() method is called
    let textbox = document.forms[0].elements["textbox1"];
    textbox.addEventListener("select".(event) = > {
        console.log(`Text selected: ${textbox.value}`);
    });
    Copy the code

    Get selected text

    The extension adds two attributes to the textbox: selectionStart and selectionEnd. These two attributes contain zero-based values that represent the start and end of the text selection (the offset of the start of the text selection and the offset of the end of the text selection). Therefore, to get the selected text in the text box, use the following code:

    function getSelectedText(textbox) {
        return textbox.value.substring(textbox.selectionStart, textbox.selectionEnd);
    }
    Copy the code

    Because the subString () method is based on a string offset, selectionStart and selectionEnd are passed directly to get the selected text.

    Older versions of IE have a Document.Selection object that contains text selection information for the entire document.

    function getSelectedText(textbox) {
        if (typeof textbox.selectionStart == "number") {
            return textbox.value.substring(textbox.selectionStart, textbox.selectionEnd);
        } else if (document.selection) {
            return document.selection.createRange().text; }}Copy the code

    This modified function is compatible with getting selected text in older versions of IE. Note that Document. Selection does not require the TextBox argument at all.

    Partially selected text

    HTML5 also provides additional support for selecting portions of text in a text box. In addition to the Select () method, Firefox’s earliest implementation of the setSelectionRange() method can now be used in all text boxes. This method takes two arguments: the index of the first character to select and the index of the character to stop selecting (as in the string substring() method). Here are a few examples:

    textbox.value = "Hello world!"
    // Select all text
    textbox.setSelectionRange(0, textbox.value.length); // "Hello world!" 
    // Select the first three characters
    textbox.setSelectionRange(0.3); // "Hel" 
    // Select the fourth to sixth character
    textbox.setSelectionRange(4.7); // "o w"
    Copy the code

    If you want to see the selection, you must set focus on the text box before or after calling setSelectionRange(). This method works in IE9, Firefox, Safari, Chrome, and Opera.

    IE8 and earlier support text selection through the range section. See the following example:

    textbox.value = "Hello world!";
    var range = textbox.createTextRange();
    // Select all text
    range.collapse(true);
    range.moveStart("character".0);
    range.moveEnd("character", textbox.value.length); // "Hello world!" 
    range.select();
    // Select the first three characters
    range.collapse(true);
    range.moveStart("character".0);
    range.moveEnd("character".3);
    range.select(); // "Hel" 
    // Select the fourth to sixth character
    range.collapse(true);
    range.moveStart("character".4);
    range.moveEnd("character".6);
    range.select(); // "o w"
    Copy the code

    As with other browsers, you must focus the text box if you want to see what is selected.

    Partially selected text is useful for advanced text entry boxes such as autocomplete suggestions.

    The input filter

    Shielding character

    If you want to mask only certain characters, you need to check the charCode property of the event to determine the correct response. For example, here is the code that allows only numbers:

    textbox.addEventListener("keypress".(event) = > {
                if (!/\d/.test(String.fromCharCode(event.charCode))) { event.preventDefault(); }}Copy the code

    This example first converts the event’s charCode to a String using string.fromCharcode () and then tests it with the regular expression /\d/. This regular expression matches all numeric characters and calls preventDefault() to mask the event default if the test fails. This allows the text box to ignore non-numeric input.

    In Firefox, all non-character keys that trigger keypress events have a charCode of 0, whereas prior to Safari 3 these keys had a charCode of 8. All of these things together, you can’t mask keys with charCode less than 10. For this, the above function can be improved to:

    textbox.addEventListener("keypress".(event) = > {
        if (!/\d/.test(String.fromCharCode(event.charCode)) && event.charCode > 9) { event.preventDefault(); }});Copy the code

    There is one more issue to deal with: copy, paste, and other functions involving the Ctrl key. In all browsers except Internet Explorer, the previous code blocks the shortcut keys Ctrl+C, Ctrl+V, and other key combinations that use Ctrl. So the final check is to make sure the Ctrl key is not pressed, as shown in the following example:

    textbox.addEventListener("keypress".(event) = > {
        if (!/\d/.test(String.fromCharCode(event.charCode)) && event.charCode > 9&&! event.ctrlKey) { event.preventDefault(); }});Copy the code

    This last change ensures that all default text box behavior is not affected. This technique allows you to customize whether certain characters are allowed to be entered in a text box.

    Handling clipboard

    Here are six clipboard-related events.

    • Beforecopy: triggered before the copy operation occurs.
    • Copy: Triggered when a copy operation occurs.
    • Beforecut: triggered before the clipping operation occurs.
    • Cut: triggered when a cut operation occurs.
    • Beforepaste: triggered before the paste operation.
    • Paste: Triggered when the paste operation occurs.

    This is a relatively new standard for controlling clipboard access, and the behavior of events and related objects varies from browser to browser. In Safari, Chrome, and Firefox, beForecopy, beforecut, and beforePaste events fire only when the context menu of a text box is displayed (in anticipation of clipboard events), but IE fires not only in this case, It also fires before copy, cut, and paste events. Copy, Cut, and Paste events fire as expected in all browsers, whether you make a selection in a context menu or use a keyboard shortcut.

    The data on the clipboard can be retrieved from the clipboardData object on the Window object (IE) or the Event object (Firefox, Safari, and Chrome). The clipboardData object has three methods: getData(), setData(), and clearData();

    function getClipboardText(event) {
        var clipboardData = (event.clipboardData || window.clipboardData);
        return clipboardData.getData("text");
    }
    
    function setClipboardText(event, value) {
        if (event.clipboardData) {
            return event.clipboardData.setData("text/plain", value);
        } else if (window.clipboardData) {
            return window.clipboardData.setData("text", value); }}Copy the code

    The getClipboardText() function here is relatively simple; all it needs to do is know where the clipboardData object is and then call getData() with the “text” type. The setClipboardText() function is a bit more complicated. After locating the clipboardData object, you need to call setData() with the appropriate type (“text/plain” for Firefox, Safari, and Chrome, “text” for IE), depending on the implementation.

    If the text box expects certain characters or text in a certain format, it helps to read the text from the clipboard. For example, if the text box allows you to enter only numbers, you must check the pasted value to make sure it contains only numbers. In paste event, you can determine if the text on the clipboard is invalid and cancel the default behavior if it is, as shown in the following example:

    textbox.addEventListener("paste".(event) = > {
        let text = getClipboardText(event);
        if (!/^\d*$/.test(text)) { event.preventDefault(); }});Copy the code

    The onPaste event handler ensures that only numbers can be pasted into a text box. If the values in the clipboard do not conform to the specified pattern, the paste operation is cancelled. Firefox, Safari, and Chrome only allow access to the getData() method in the onPaste event handler.

    Automatic switch

    JavaScript can enhance the usability of form fields in many ways. The most common is to automatically switch to the next field when the current field is complete.

    In the United States, a telephone number is usually divided into three parts: the area code, the switching office code, and four digits. In a web page, these sections can be represented by three text boxes, such as:

    <input type="text" name="tel1" id="txtTel1" maxlength="3">
    <input type="text" name="tel2" id="txtTel2" maxlength="3">
    <input type="text" name="tel3" id="txtTel3" maxlength="4">
    Copy the code

    To increase the ease of use of this form and speed up data entry, you can automatically switch focus to the next text box as each text box is entered to the maximum number of characters allowed. Therefore, when the user enters three characters in the first text box, the focus moves to the second text box, and when the user enters three characters in the second text box, the focus moves to the third text box. This behavior of automatically switching text boxes can be implemented with the following code:

    function tabForward(event) {
        let target = event.target;
        if (target.value.length == target.maxLength) {
            let form = target.form;
            for (let i = 0, len = form.elements.length; i < len; i++) {
                if (form.elements[i] == target) {
                    if (form.elements[i + 1]) {
                        form.elements[i + 1].focus();
                    }
                    return; }}}}let inputIds = ["txtTel1"."txtTel2"."txtTel3"];
    for (let id of inputIds) {
        let textbox = document.getElementById(id);
        textbox.addEventListener("keyup", tabForward);
    }
    let textbox1 = document.getElementById("txtTel1");
    let textbox2 = document.getElementById("txtTel2");
    let textbox3 = document.getElementById("txtTel3");
    Copy the code

    HTML5 constraint validation API

    HTML5 adds the ability for browsers to validate data before submitting forms.

    Validation is applied to form fields based on certain criteria. You can use HTML tags to specify constraints on specific fields, and the browser automatically performs form validation based on those constraints.

    Required fields

    The first condition is to add the required attribute to the form field, as shown below:

    < input type = "text"
    name = "username"
    required >
    Copy the code

    You can determine if a form field is required by JavaScript by detecting the required attribute of the corresponding element:

    let isUsernameRequired = document.forms[0].elements["username"].required;
    Copy the code

    You can also check if the browser supports the required attribute using the following code:

    let isRequiredSupported = "required" in document.createElement("input");
    Copy the code

    This line of code uses a simple feature check to determine whether the required attribute exists on the newly created element.

    Note that different browsers have different mechanisms for processing required fields. While Firefox, Chrome, IE, and Opera block form submission and display help pop-ups under the corresponding fields, Safari does nothing and does not block form submission.

    More Input types

    HTML5 adds several new type values to elements. Two of the new input types are the already widely supported “email” and “URL”, both of which have browser-provided custom validation.

    <input type="email" name="email">
    <input type="url" name="homepage">
    Copy the code

    Numerical range

    HTML5 also defines several new input element types that expect some kind of numeric input, including “number”, “range”, “datetime”, “datetime-local”, “date”, “month”, “week”, and “time”. Not all major browsers support these types, so be careful when using them

    The input mode

    HTML5 has added a pattern attribute to text fields. This property is used to specify a regular expression that the text entered by the user must match.

    For example, to restrict entry of numbers only to text fields, add patterns like this:

    <input type="text" pattern="\d+" name="count">
    Copy the code

    Note that the beginning and end of the pattern assume ^ and $, respectively. This means that the input must strictly match the pattern from beginning to end.

    The pattern can be read by accessing the pattern property:

    let pattern = document.forms[0].elements["count"].pattern;
    Copy the code

    To check whether the browser supports the Pattern attribute, use the following code:

    let isPatternSupported = "pattern" in document.createElement("input");
    Copy the code

    Test validity

    The checkValidity() method can be used to check whether any given field in the form is valid. This method can be used on all form elements and returns true if the field value is valid and false otherwise.

    if (document.forms[0].elements[0].checkValidity()) {
        // The field is valid, continue
    } else {
        // The field is invalid
    }
    Copy the code

    To check whether the entire form is valid, you can call the checkValidity() method directly on the form. This method returns true if all fields are valid and false if one field is invalid:

    if (document.forms[0].checkValidity()) {
        // The form is valid, continue
    } else {
        // The form is invalid
    }
    Copy the code

    The checkValidity() method only tells us if the field is valid, and the validity attribute tells us why the field is valid or invalid. This property is an object containing a set of properties that return a Boolean value.

    • CustomError: Return true if setCustomValidity() is set, false otherwise.
    • PatternMismatch: Returns true if the field value does not match the specified Pattern attribute.
    • RangeOverflow: Returns true if the field value is greater than the value of Max.
    • RangeUnderflow: Returns true if the field value is less than min.
    • StepMisMatch: Return true if the field values do not match min, Max, or step.
    • TooLong: Returns true if the length of the field value exceeds the value specified by the maxLength attribute. Some browsers, such as Firefox 4, automatically limit the number of characters, so this property value is always false.
    • TypeMismatch: Returns true if the field value is not in the format required by “email” or “URL”.
    • Valid: Returns true if all other attributes are false. Consistent with the condition of checkValidity().
    • ValueMissing: Returns true if the field is mandatory but has no value.

    Therefore, the validity of form fields can be checked through the validity attribute to obtain more specific information, as shown in the following code:

    if(input.validity && ! input.validity.valid) {if (input.validity.valueMissing) {
            console.log("Please specify a value.")}else if (input.validity.typeMismatch) {
            console.log("Please enter an email address.");
        } else {
            console.log("Value is invalid."); }}Copy the code

    Disable validation

    You can disable any validation of the form by specifying the novalidate attribute:

    <form method="post" action="/signup" novalidate>
        <! -- Form elements -->
    </form>
    Copy the code

    This value can also be retrieved or set via the JavaScript property noValidate, which is true to indicate that the property exists and false to indicate that it does not exist:

    document.forms[0].noValidate = true; // Disable validation
    Copy the code

    If you have multiple submit buttons in a form, you can add the FormNovalidate attribute to that particular submit button to specify that the form can be submitted without validation:

    <form method="post" action="/foo">
        <! -- Form elements -->
        <input type="submit" value="Regular Submit">
        <input type="submit" formnovalidate name="btnNoValidate" value="Non-validating Submit">
    </form>
    Copy the code

    In this example, the first submit button allows the form to validate the data as usual, while the second button disables validation and can submit the form directly. We can also use JavaScript to set this property:

    // Disable validation
    document.forms[0].elements["btnNoValidate"].formNoValidate = true;
    Copy the code

    Select box programming

    The selection box is created using the <select> and <option> elements. To facilitate interaction, the HTMLSelectElement type provides the following properties and methods in addition to the common capabilities of all form fields.

    • Add (newOption, relOption) : Adds a new
    • Multiple: Boolean value indicating whether multiple selection is allowed, equivalent to the HTML multiple attribute.
    • Options: HTMLCollection of all
    • Remove (index) : indicates the option to remove a given position.
    • SelectedIndex: The index value based on 0 for the selected item, or -1 if no selected item is selected. For lists that allow multiple selections, always the index of the first option.
    • Size: The number of lines visible in the selection box, equivalent to the SIZE attribute of HTML.

    The type attribute of the selection box may be “select-one” or “select-multiple”, depending on whether the multiple attribute exists. The currently selected item determines the value property of the selection box according to the following rules.

    • If no item is selected, the value of the selection box is an empty string.
    • If there is a selected item and its value property has a value, the value of the selection box is the value of the value property of the selected item. This is true even if the value of the value attribute is an empty string.
    • If there is a selected item whose value attribute does not specify a value, the value of the selection box is the text content of the item.
    • If there are more than one selected item, the value of the selection box takes the value of the first selected item according to the first two rules.

    Take a look at the selection box below:

    <select name="location" id="selLocation">
        <option value="Sunnyvale, CA">Sunnyvale</option>
        <option value="Los Angeles, CA">Los Angeles</option>
        <option value="Mountain View, CA">Mountain View</option>
        <option value="">China</option>
        <option>Australia</option>
    </select>
    Copy the code

    If the first item in the checkbox is checked, the value of the field is “Sunnyvale, CA”. If an item with text “China” is selected, the value of the field is an empty string because the value attribute of the item is an empty string. If the last item is selected, the value of the field is “Australia” because the element does not specify a value attribute.

    Each element is represented in the DOM by an HTMLOptionElement object. The HTMLOptionElement type adds the following attributes to facilitate data access.

    • Index: Index of an option in the options collection.
    • Label: The label of the option, equivalent to the LABEL attribute of HTML.
    • Selected: Boolean value, indicating whether the current option is selected. Setting this property to true selects the current option.
    • Text: indicates the text of the option.
    • Value: The value of the option (equivalent to the HTML value attribute).

    Most attributes are for easy access to option data. You can access this information using normal DOM functionality, but inefficiently, as shown in the following example:

    let selectbox = document.forms[0].elements["location"];
    / / do not recommend
    let text = selectbox.options[0].firstChild.nodeValue; // Option text
    let value = selectbox.options[0].getAttribute("value"); / / option value
    Copy the code

    The code above uses standard DOM techniques to get the text and value of the first option in the selection box. Compare the code using the special option attribute:

    let selectbox = document.forms[0].elements["location"];
    / / recommend
    let text = selectbox.options[0].text; // Option text
    let value = selectbox.options[0].value; / / option value
    Copy the code

    Finally, the change event of the selection box is not the same as other form fields. Other form fields fire the change event when their values change, and the fields lose focus. The selection box triggers the change event immediately when an item is selected.

    Option to deal with

    For a selection box that allows only one item to be selected, the easiest way to get the option is to use the selectedIndex property of the selection box, as shown in the following example:

    let selectedOption = selectbox.options[selectbox.selectedIndex];
    Copy the code

    This will get all the information about the options, such as:

    let selectedIndex = selectbox.selectedIndex;
    let selectedOption = selectbox.options[selectedIndex];
    console.log(`Selected index: ${selectedIndex}\n` +
        `Selected text: ${selectedOption.text}\n` +
        `Selected value: ${selectedOption.value}`);
    Copy the code

    The above code prints out the index of the selected item with its text and value.

    For checkboxes that allow multiple selections, the selectedIndex property is as good as allowing only one selection. Setting selectedIndex removes all options and selects only the specified item, while fetching selectedIndex returns only the index of the first selected item.

    How to get multiple selected values: The Selected property determines which option in the selection box is selected. To get all the selected items, loop through the selected property one by one, for example:

    function getSelectedOptions(selectbox) {
        let result = new Array(a);for (let option of selectbox.options) {
            if(option.selected) { result.push(option); }}return result;
    }
    Copy the code

    Add a option

    You can use JavaScript to create options dynamically and add them to the selection box.

    Method 1: You can use the DOM method, as shown below:

    let newOption = document.createElement("option");
    newOption.appendChild(document.createTextNode("Option text"));
    newOption.setAttribute("value"."Option value");
    selectbox.appendChild(newOption);
    Copy the code

    The above code creates a new element, adds text using the text node, sets its value property, and then adds it to the selection box. The new option is displayed immediately after it is added to the selection box.

    Method two: The Option constructor, which was supported by browsers before DOM existed, creates a new Option.

    The Option constructor takes two arguments: text and value, where value is optional. Although this constructor normally creates an instance of Object, DOM-compliant browsers return an element. This means that you can still add this created option to the selection box using the appendChild() method. Take the following example:

    let newOption = new Option("Option text"."Option value");
    selectbox.appendChild(newOption); // There is a problem in IE8 and earlier
    Copy the code

    Method 3: Use the add() method of the checkbox

    DOM specifies that this method takes two parameters: the new option to add and the reference option to add in front of it. If you want to add options to the end of the list, the second argument should be NULL.

    Dom-compliant browsers require passing in a second parameter, so you can’t just use one parameter in a cross-browser method. Passing undefined as the second parameter ensures that the option is added to the end of the list in all browsers.

    let newOption = new Option("Option text"."Option value");
    selectbox.add(newOption, undefined); // Best case scenario
    Copy the code

    The above code works with all versions of Internet Explorer and DOM compliant browsers. If you don’t want to insert new options at the end, you should use DOM technology and insertBefore().

    Remove options

    Like adding options, there is more than one way to remove options.

    Method one: Use DOM’s removeChild() method and pass in the option to remove,

    selectbox.removeChild(selectbox.options[0]); // Remove the first item
    Copy the code

    Method 2: Use the remove() method of the selection box. This method takes an argument, the index of the option to remove,

    selectbox.remove(0); // Remove the first item
    Copy the code

    Method 3: Directly set the option to null. This is also how browsers were implemented before DOM.

    selectbox.options[0] = null; // Remove the first item
    Copy the code

    To clear the selection box of all options, iterate over all options and remove them one by one, as shown in the following example:

    function clearSelectbox(selectbox) {
        for (let option of selectbox.options) {
            selectbox.remove(0); }}Copy the code

    This function removes each item in the selection box one by one. Because removing the first item automatically moves all options forward one notch, this removes all options.

    Move and rearrange options

    The DOM method moves an option directly from the first selection box to the second by using the appendChild() method on the corresponding option.

    let selectbox1 = document.getElementById("selLocations1");
    let selectbox2 = document.getElementById("selLocations2");
    selectbox2.appendChild(selectbox1.options[0]);
    Copy the code

    The insertBefore() method is the best way to move an option to a specific location in the selection box. However, the appendChild() method is more convenient to move the option to last

    The following code demonstrates moving an option forward one position in the selection box:

    let optionToMove = selectbox.options[1];
    selectbox.insertBefore(optionToMove,
        selectbox.options[optionToMove.index - 1]);
    Copy the code

    This example first gets the index of the option to move and then inserts it before the previous option, where the second line applies to all options except the first option. The following code moves the option down one position:

    let optionToMove = selectbox.options[1];
    selectbox.insertBefore(optionToMove,
        selectbox.options[optionToMove.index + 2]);
    Copy the code

    Form serialization

    Before writing the code, we need to understand how the browser determines what to send to the server when submitting the form.

    • Field names and values are URL-encoded and separated by an ampersand (&).
    • Disabled fields will not be sent.
    • Check boxes or radio buttons are sent only when they are selected.
    • Buttons of type “reset” or “button” will not be sent.
    • Each selected item in a multi-selected field has a value.
    • The submit button is sent when the form is submitted by clicking the Submit button; Otherwise, the submit button is not sent. elements of type “image” are considered submit buttons.
    • The value of the

    Rich text editor

    There are two ways to do this: the first is iframe and the second is contenteditable;

    Interacting with rich text

    The primary way to interact with a rich text editor is to use document.execcommand ().

    The first method is queryCommandEnabled(), which determines whether commands can be executed for the currently selected text or cursor position.

    Another method, queryCommandState(), is used to determine whether the relevant command applies to the current text selection.

    The last method is queryCommandValue(), which returns the value used when executing the command

    Rich file selection

    Use the getSelection() method in an inline pane to get a selection for a rich text editor.

    Submit rich text through the form

    Because rich text editing is done in inline panes or by specifying contenteditable attributes for elements, rather than in form controls, rich text editors are not technically related to forms. This means that to submit the results of rich text editing to the server, you must manually extract the HTML and submit it yourself.

    form.addEventListener("submit".(event) = > {
        let target = event.target;
        target.elements["comments"].value =
            frames["richedit"].document.body.innerHTML;
    });
    Copy the code