JavaScript form Programming

Source: Internet
Author: User

First, script the form element

JavaScript can access forms in an HTML document through the child object Form object of the Document object (the Htmlformelement object in the DOM).

1. Get a reference to a form

Before scripting the form, we have to get a reference to the form element:

    • Use the method of locating an element in the DOM tree, using the getElementById () method, and use the ID of the form as the parameter of the method;

document.getElementById ("ID number")

    • Use the form collection for the document, and either through the form's position in the form collection or through its Name property;

document.forms[0];//Get the first form

document.forms["Formz"];//get a form named Formz

2. Accessing form fields

Each form field is included in the form's element collection, and can be accessed by using the form's Name property or his location in the collection to access the different fields in the collection.

1) oform.elements[0];//Get the first form field

2) oform.elements["TextBox1"];//get field named TextBox1

3) oform.textbox1;//get the field named TextBox1

4) If there is a space between the names, you can replace them with brackets:

Oform. ["Text Box1"];//get field named TextBox1

3. form Field commonality

The fields of all forms (except hidden fields) have the following common properties, methods, and events:

    • The Disabled property is used to indicate whether a form control is available with a disabled control that does not allow user input.
    • The Form property returns the form that contains the field.
    • Blur () Method: This method causes the form field to lose focus.
    • Focus () Method: This method causes the form field to get focus.
    • Blur Event: The event occurs when the form field loses focus, and then the onblur event handler is executed.
    • Focus Event: The event occurs when the form field has the focus, and then the onfocus event handler is executed.

For example:

var v1=oform.elements[0];

var v2=oform.elements[1];

Set the first field to not available

V1.disabled=true

Set focus in second field

V2.focus ();

Determines whether the form property of a field equals oform

alert (v1.form==oform);//Output True

4. Form submission

In XHTML, we use a submit button or a graphic that simulates the submit button to submit the form.

<input type= "Submit" value= "Submit"/>

<input type= "image" src= "Submit.gif"/>

To submit a form, you first get a reference to the form element. Once we get the form reference, we can call the Submit () method directly;

Oform.submit ();

After the Submit button is clicked, the submit event is triggered and the OnSubmit event handler is executed. Using the OnSubmit event handler, you can abort the form submission, which is particularly useful when validating client data. Aborting a form submission is, in fact, the default behavior of blocking events.

Function Handlesubmit () {

return false;

}

We can then call this method in the form's OnSubmit event handler:

<foem method= "POST" action= "#" onsubmit= "Handlesubmit ()" >

5. Form Reset

Using the reset button in XHTML gives the user a way to reset all form fields to their default values, which resets the form directly from the script and does not require a script to tell the browser what to do:

<input type= "reset" value= "reset"/>

Second, script the text box

In HTML, the text boxes for the two main input text are: single-line version of <input type= "text"/> and multi-line version of the <textarea/>.

1. Get/Change the value of the text box

Although <input type= "text"/> and <textarea/> are different elements, they all support the same property vlaue to get the text of the text box:

<! DOCTYPE html>

<meta charset= "UTF-8" >

<title></title>

<script type= "Text/javascript" >

function GetValues () {

var V1=document.getelementbyid ("Txt1");

var V2=document.getelementbyid ("Txt2");

Alert (the value of "txt1" is \ "" "+v1.value+" \ "\ n" + "TXT2" the value is \ "" "+v2.value+" \ ")

}

</script>

<body>

<input type= "text" size= "id=" Txt1 "/><br/>"

<textarea rows= "5" cols= "id=" Txt1 "/><br/>"

<input type= "button" value= "Get Value" onclick= "getValues ()"/>

</body>

This example now shows one but a line text box, a multiline text box, and a button. When you click the button, a warning dialog box displays the value of each text box. Use the Length property to get the amount of text in the box worth:

Alert (the length of "txt1" is \ "" + v1.value.length + "\" \ \ \ "+" txt2 "is the length of \" "+ v2.value.length +" \ "")

}

The property value can also be used to assign a new value to a text box:

v1.value= "First text box";

V2.value= "Second text box";

2. Select text

Both types of text boxes support the Select () method, which is used to select all the text in the text box. For this method to work, the text box must have the focus. And you must call the focus () method before the Select () method.

3. Text Box Events

Both text boxes support blur, focus, change, and select events.

The Change event occurs after the user changes the value of the text box when the text box loses focus. However, the change event is not triggered when the value of the text box is changed by setting the Values property.

The Select event occurs when one or more characters are selected, whether manually selected or by using the Select () method.

The Blur event is triggered when the text box loses focus, and the value of the text box does not change.

4. Automatically select text

To automatically select all the text in the text box when the text box is focused, we can use the Select () method in the Onfocus event handler of the text box:

<input type= "text" onfocus= "This.select ()"/>

<textarea onfocus= "This.select ()"/><textarea/>

Iii. Scripting list boxes and combo boxes

1. Access Options

To get the display text and values of an OPTION element in the Select control, you can use the DOM feature:

V=document.getelementbyid ("Selectid");

alert (v.options[1],firstchild.nodevalue);//Output display text

Alert (V.options[1],getattribute ("value"));//Output value

You can also use two specific OPTION element attributes in the HTML DOM: text and value;

alert (v.options[1],text);//Output display text

alert (v.options[1],value);//Output value

Each option element also has an index property that indicates its position in the collection:

alert (v.options[1],index);//Output 1

2. Get/Change options

The SelectedIndex property of the Select element, which returns the index of the currently selected option, returns 1 if not selected, and the Multiple property of the Select element to "multiple", which allows the drop-down list to be selected multiple items (combo box cannot);

Alert ("Selected index is" + V.selectedindex);

SelectedIndex contains only the index number of the first selected item, and multiple selected items cannot be displayed. To do this, we created a custom method, Getselectedindexes (). The Getselectedindexes () method takes advantage of another special attribute of the OPTION element: the Select property. Defining a Select Property in the HTML DOM is a Boolean value that indicates whether an option is selected.

The Getselectedindexes () method can be used to get the index of multiple selected items, or the length of the array returned is judged by how many options are selected.

3. Add options

To dynamically add options to the Select element, there are several steps:

1) Define a method with three parameters, each of which is the list box for the option to be added, the name of the option to add, and the value of the option to add.

2) Use the DOM method to create an option element, and then create a text node to assign the name to the option.

3) Set the Value property of the OPTION element.

4) Add the new option to the Select element by using the AppendChild () method.

4. Delete options

There are two ways to delete an option, one that is provided by the DOM, and one that is provided by the HTNL DOM.

The functionality provided by the DOM is: Use the option collection and set the option to remove to null:

V.options[1]=noll;

The DOM provides the ability to use the Remove () method of the Select element to pass the index of the option to be removed to the Remove () method:

Var V=document.getelementbyid ("Selectid");

v.remove[0];//removing the first option

5. Move Options

The Remove option can use the DOM's AppendChild () method to move the options from the first list box one by one to the second list box. If we pass an element in a document to the AppendChild () method, the element is moved out of its parent element and placed in the specified position.

First write a method and let it receive three parameters: the list box that is currently selected, the list box to which you want to move the option, the index of the options to be moved, and the move the given option to another list box.

6. Reorder Options

To reorder the options in the list box, we need two methods: one to move the options up and one to move the options down. Each method has two parameters: the list box to function, the index of the option to move. Both methods need to use the DOM's InsertBefore () method to reorder the option elements.

It is important to note that the move-up method first checks whether the index of the option is greater than 0, because we cannot move the first option upward. The same is true for moving down, but checking the last option.

var V=document.getelementbyid ("Selectid");

Listutil.shiftup (v,1);//move the option with index 1 up one position

Listutil.shiftdown (v,2); Move the option with index 2 down one position

Iv. scripting check boxes and Radio boxes

check boxes and radio boxes are related to objects, in addition to the properties of objects that are common to other input elements, there are some other properties:

Checked: Boolean value indicating the state of the space;

Defaultchecked: Boolean value indicating whether the control is selected when the page is loaded;

Click (): Imitate the button clicks, change the space state, the corresponding time onclick;

1. Get the value of the Radio box

You get the value of a radio box by using the Value property of the Radio box:

document.getElementById ("Selectid"). Value;

2. Get the value of the check box

The use of the value to get a check box is basically the same as a radio box, and the difference is that multiple check boxes are allowed to be selected, so the resulting value is also multiple:

<script type= "Text/javascript" >

function GetValues () {

var V=document.getelementbyid ("MyForm"). Cities;

for (i=0,i<ochecks.length;i++) {

if (ochecks[i].checked) {

alert (Ochecks[i].value);

}}}

</script>

V. Forms validation

Using the Submit event to catch an error after an error occurs

After the form data has been entered, click the Submit button or use the OnSubmit () method to send the form to the form handler specified by the form's Action property for processing. To prevent unwarranted data from entering the server, we can verify that the validation code is written to the submit event handler before the form is submitted to the form handler before the Submit event occurs. The data is invalid and the handler returns a value of False to cancel the commit. The data is valid, the handler returns a true value, and the commit succeeds.

<form id= "MyForm" method= "Post" antion= "#" onsubmit ("return validate (); ") >

JavaScript form Programming

Related Article

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.