JavaScript Advanced Programming Notes (14)

Source: Internet
Author: User

form scripting (i) Basics of forms 1. Submit Form

The submit button is defined by using <input> or <button> setting its type attribute to submit, and the picture button is defined by setting the <input> type attribute value to "image".

Use the Preventdefault () method to block form submission. This is typically done when the form data is invalid and cannot be sent to the server.

// Get Event Object = eventutil.getevent (events); // Block Default Events Eventutil.preventdefault (event);

You can also submit a form programmatically, without triggering a submit event, so validate the form data before committing.

Submit a form repeatedly: The Submit button is disabled after the form is first submitted, or the subsequent form submission is canceled with the OnSubmit event handler.

2. Reset the form

When the user taps the reset button, the reset event is triggered, and we can cancel the reset operation if necessary. Calling the Reset () method recalls clicking the Reset button to trigger the reset event.

3. Form fields

Each form has a elements property, which is a collection of all the form elements in the form that can be accessed by location and name attributes.

If multiple form controls use a name, the first nodelist of that name is returned.

① Common form Field properties

In addition to <fieldset> all form fields have a common set of properties.

The ability to dynamically modify form fields means that we can dynamically manipulate the form in any way at any time.

               // avoid multiple mentions of forms               function (event) {                = eventutil.getevent (event);                 var target = eventutil.gettarget (event);                             // Get Submit button                var btn = target.elements["submit-btn"];                             // Disable it                true;

cannot be implemented with the OnClick event handler because a browser will trigger the Click event before the Submit event of the published order is touched.

form field methods common to ②

There are two methods for each form field: Focus () and Blur ().

The focus method is used to set the browser focus to form fields so that they can respond to keyboard events.

HTML5 adds the Autofocus property to the form field, moving the focus to the fields of the response. The supported browser value is true.

<input type= "Text" autofocus>

firefox4+, safari5+, Chrome and opera.

Blur () removes the focus from the element and does not shift the focus to a particular element.

③ Public form Field events

In addition to supporting mouse, keyboard, change, and HTML events, all form fields support 3 events.

Blur: Triggered when the bullet loses focus.

Change: For <input> and <textarea> elements, where they lose focus and value changes, and on <select> elements, triggered when their options change.

Focus: The current field gets the focal point.

You can use the focus event to modify the background color of the text box to make it clearer that the field has the focus, use the Blur event to restore the background color, and use the Change event to modify the background color again when the user enters a non-numeric character.

(ii) text box script

Text boxes: one-line text boxes that use the <input> element, and a multiline text box that uses <textarea>.

text box to set the type attribute of the <input> element to "text", the size attribute specifies the number of characters the text box can display, value sets the initial value, and maxlength specifies the maximum number of characters to accept.

Multiline text box with rows good cols Specify the number of rows and columns,<textarea> The initial value to be placed between <textarea> and </textarea>, and cannot be given <textarea in HTML > Specifies the maximum number of characters.

They all save user-entered content to the Value property.

1. Select text

The Select () method is used to select all text in the text box, especially if the text box contains a default value when the user does not delete the text.

① Select Event

In ie9+, Opera, Firefox, Chrome and Safari, only the user selects text (and releases the mouse) to trigger the Select event in IE8 and earlier, as long as the user chooses a letter (without releasing the mouse). The Select event is also triggered when the Select method is called.

② Get the selected text

Add Properties SelectionStart and Selectionend to get the selected text. These two properties hold a numeric value based on 0, representing the range of selected text.

Textbox.value.substring (Textbox.selectionstart,  textbox.selectionend)

Because the substring () method is based on the string offset operation, the SelectionStart and Selectionend are passed directly to it.

IE8 and previous versions do not support these two properties, they have document.selection objects that hold the text information that the user selects throughout the document. Use with the Select event and create a range to extract the text.

Document.selection.createRange (). text;

③ Select some text

The Setselectionrange () method receives two parameters: the index of the first character to select and the character after the last character.

To see the selected text, you must set the focus to the text box immediately before or after calling Setselectionrange ().

IE9, Firefox, Safari, Chrome, and opera support.

IE8 and previous versions support the use of the range selection section text. First use the createTextRange () method to create a range and place it in the appropriate place. Then use collapse () to collapse the range to the beginning of the text box, calling MoveStart () and MoveEnd () to move the range into place. Finally, select the text using the range's Select () range.

2. Filter input

① Masked characters

Block all keystrokes by blocking the default behavior of the event

function(event) {                event = eventutil.getevent (event);                Eventutil.preventdefault (event);                          }); 

To block specific characters:

Eventutil.addhandler (textbox, "KeyPress",function(Event) {event=eventutil.getevent (event); vartarget =Eventutil.gettarget (event); varCharCode = Eventutil.getcharcode (event);//get character encoding across browsers                if(!/\d/.test (String.fromCharCode (charcode)) && charcode > 9 &&!event.ctrlkey) {//fromCharCode converts a character encoding to a string!event.ctrlkey: The CTRL key is not pressedEventutil.preventdefault (event); }                            });

② manipulating the Clipboard

Beforecopy copy beforecut cut beforepaste paste

To access the Clipboard data you can use the Clipborddata object: In IE this is the property of the Window object, which is the property of the corresponding event in Firefox 4+, Safari, Chrome. In Firefox, Safari, and Chrome, Clipboarddata objects are valid only during clipboard events, and Clipboarddata objects can be accessed at any time in IE.

There are 3 methods of Clipboarddata objects: GetData (), SetData (), ClearData ().

GetData () receives a parameter, which is the data format to be obtained. IE has "text" and "URL", and Firefox, Safari and Chrome are MIME types, but you can use "text" to represent "Text/plain".

SetData () The first parameter is also the data type, Safari and chrome only support MIME types, and the second parameter is the text to be placed on the Clipboard. Safari and Chrome's SetData () method does not recognize the "text" type and returns true after the script is successfully placed.

                if (!/^\d*$/. Test (text)) {                    Eventutil.preventdefault (event);                }

Not all browsers support access to the Clipboard, and it's easier to block one or more clipboard operations, where opera needs to block keystrokes that trigger these events, and prevents text boxes from displaying context menus.

3. Automatically switch focus
            functionTabforward (Event) {event=eventutil.getevent (event); vartarget =Eventutil.gettarget (event); if(Target.value.length = =target.maxlength) {                    varform =Target.form;  for(varI=0, Len=form.elements.length; i < Len; i++) {                        if(Form.elements[i] = =target) {                            if(form.elements[i+1]) {form.elements[i+1].focus (); }                            return; }                    }                }            }

Compares the value entered by the user with the MaxLength property of the text box to determine whether the maximum length is reached. If they are equal, you need to find the form field collection until you find the next text box. When found, switches the focus to the text box. This function is then specified as the OnKeyUp event handler for each text box.

4.HTML5 Constraint Validation API

HTML5 adds features that ensure basic validation even if JavaScript is disabled or not loaded. Support for Firefox 4+, Safari 5+, Chrome and opera.

① Required Fields

The first case is to specify the required property in the form field

<input type= "text" name= "username" required>

Applies to <input> <textarea> and <select> fields.

② Other input types

Email and URL Properties

<input type = "Email" name = "Email" ><input type = "url" name = "Homepage" >

The "email" attribute requires that the entered text conform to the mode of the e-mail address, and the URL requires that the text entered conform to the URL pattern. However, there is a problem with the matching pattern. If you do not set the Required property to the <input> element, the empty text box will pass validation.

③ Data range

"Number" "Range" "datetime" "tatetime-local" "Date" "Month" "Week" "Time", but browser support is not ha.

For all input elements of these numeric types, you can specify the Min property, the Max property, and the Step property.

Stepup () and Stepdown (), which receive an optional parameter: The number to be added or subtracted from the current value base.

④ Input Mode

HTML5 adds the Pattern property to the text, and the value is a regular expression that matches the value in the text box.

// only allow input number <input type= "text" pattern= "\d+" name= "Count" >

Specifies that pattern does not prevent users from entering invalid text.

⑤ Detection Effectiveness

The Checkvalidity () method can detect if a field in the form is valid, if the field returns true effectively. Whether the field value is valid is based on the preceding constraint. To detect whether the entire form is valid, you can call this method on the form itself.

The Validity property contains a series of properties, each of which returns a Boolean value that indicates whether the value conforms to the constraint.

⑥ Disabling authentication

The Novalidate property is set, and the form is not validated.

If a form has multiple submit buttons, to specify that clicking on a Submit button does not validate the form, you can add the Formnovalidate property to the corresponding button.

(c) Select box Script

Created through <select> and <option>.

Htmlselectelement Type:

Add (newoption,reloption): Inserts a new <option> element into the plug-in, positioned before reloption.

Multiple: Boolean value, whether multiple selections are allowed.

Options: Htmlcollection of all <option> elements.

Remove (Index): Removes the option from the specified location.

SelectedIndex: The index of the selected item based on 0. There is no checked item value of-1. Multiple selection values keep the first item of the selected item.

Size: The number of rows visible in the selection box.

The Value property of the Options box:

Not checked: empty string.

There is a check, and the value attribute is specified in HTML: equals the value attribute, even if value is an empty string.

There is a check that the value attribute is not specified in HTML: equals the text of the item.

There are multiple selected items: The value of the first selected item is obtained according to the first two rules.

Htmloptionelement type

Index: Currently selected in the indexed option.

Selected: Whether the current option is selected,

The text of the option.

Value: The values of the options.

var selectbox = document.forms[0].elements["Location"]; // Recommended var text = Selectbox.option[0].text;      // text of the option var text = Selectbox.option[0].value;    // The value of the option

When the value attribute is not specified, IE returns an empty string, ie9+, Safari, Firefox, Chrome, and opera return the same value as the text attribute.

1. Select options

The SelectedIndex property accesses the selected item

var selectedoption = Selectbox.option[selectbox.selectedindex];

For a selection box that selects multiple items, the SelectedIndex property cancels all previous options and selects the specified item.

Another way to select options-Get a reference to an item and set its Selected property to True. The Allow multiple selection box setting does not cancel the selection of other options. However, it is canceled in the radio selection box. Setting selected to False has no effect on the radio selection box.

2. Add options

Method One: DOM

Create the <option> element, add a text node for it, and set the value attribute to add it to the selection box.

                var newoption = document.createelement ("option");                Newoption.appendchild (document.createTextNode (Texttextbox.value));                Newoption.setattribute ("value", Valuetextbox.value);                                Selectbox.appendchild (newoption);

Method Two: Option constructor

Receive two parameters text, value (optional)

var New Option ("option text", "option value"); Selectbox.appendchild (newoption);     // bug in IE8 and previous versions

Method Three: Select the box's Add () method

Receive two parameters: The new option to add and the option to be placed after the new option, the second parameter passed in to undefined to insert the new option into the list at the end of all browsers.

var New Option ("option text", "option value"); Selectbox.add (newoption, undefined);

3. Remove Options

Method One: Dom's RemoveChild () method

Selectbox.removechild (Selectbox.option[0]);

Method Two: Select the Remove () method of the box to receive a parameter: The index of the option to remove

Selectbox.remove (0);

Method Three: Set the appropriate option to NULL

null;

When you remove an option, subsequent options automatically move up one position.

4. Move and rearrange options

Move an option box's options to another option box--Use the DOM's AppendChild method

Selectbox2.appendchild (Selectbox1.options[parseint (Textbox.value, 10)]);

To move an item to a specific location, the most appropriate Dom method is insertbefore ()

// move forward one option in the Options box selectbox.insertbefore (Optiontomove, selectbox.options[optiontomove.index-1]);   Backwards is index+2.

(iv) Serialization of forms

Use the Type property to implement form serialization together with the name and Value property.

(v) Rich text editing

The essence is to embed an IFRAME in the page that contains an empty HTML page. By setting the DesignMode property, this blank HTML page can be edited, and the edit object is the HTML code for the page <body> element. When the DesignMode property value is on, the entire document is editable.

The onload event is used only when the page has finished loading to set the DesignMode property.

1. Using the Contenteditable property

You can apply the Ontenteditable property to any element on the page, and the user can edit the element. There are three possible values for true, false, inherit.

IE, Firefox, Chrome, Safari and Opera

2. Manipulating Rich Text

The main way to interact with a rich text editor is to use Document.execcommand (). This method executes a predefined command on a document, passing three parameters: the name of the command to execute, indicating whether the browser should provide a Boolean value for the user interface for the current command and a value to execute the command (NULL is not required). The second parameter is set to False to keep the browser compatibility.

The commands associated with the clipboard vary widely in different browsers.

The HTML generated by these commands is very different in different browsers.

queryCommandEnabled (): Detects whether a command can be executed against the currently selected text or the current caret location, receives a parameter that is the command to be detected, and returns true if the command is allowed to execute.

Querycommandstate (): Determines whether the enactment command has been applied to the selected text.

Querycommandvalue (): Gets the value passed in when the command is executed.

3. Rich Text selection

Use the GetSelection () method of the frame to determine the text that is actually selected. Calling it returns a Selection object that represents the currently selected text.

Use the DOM range in the default selection to add a selection to the <span> element with a yellow background through the surroundcontents () method.

                            var selection = frames["RichEdit"].getselection ();                                                         // get a range                            of Representative constituencies var range = selection.getrangeat (0);                                                         // Highlight the selected text                            var span = frames["RichEdit"].document.createelement ("span");                             = "Yellow";                            Range.surroundcontents (span);

IE9, Firefox, Safari, Chrome, Opera 8 all implement it, IE8 and previous versions can manipulate the selected text by Selection objects.

4. Forms and Rich Text

HTML for Rich Text editor is not automatically submitted to the server, we need to manually extract and submit HTML. You can usually add a hidden form field so that its value equals the HTML extracted from the IFRAME.

            function () {                = eventutil.getevent (event);                 var target = eventutil.gettarget (event);                            target.elements["comments"].value = frames["RichEdit"].document.body.innerhtml;            });

Gets the HTML of the IFRAME through the innerHTML property of the document body, inserting it into the form field of "comments". You must do this if you want to submit the form manually through submit () in your code.

JavaScript Advanced Programming Notes (14)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.