A technique for getelementbyid usage

Source: Internet
Author: User

Assume that the textbox1 character is copied to textbox2 in real time. The Code is as follows:

<Script language = "JavaScript">
Function copystr ()
{
Document. getelementbyid ("textbox2"). value = Document. getelementbyid ("textbox1"). value;
}
</SCRIPT>

<Form name = "form1" method = "Post" Action = "default. aspx" id = "form1">
<Input name = "textbox1" type = "text" id = "textbox1" onkeyup = "copystr ()"/> <br/>
<Input name = "textbox2" type = "text" id = "textbox2"/>
</Form>

The above code can work well. However, I think the document on the equal sign side 2. getelementbyid ("... ") the code is too long. You want to assign them to two variables before using them. Another benefit is that when document. getelementbyid ("...") is used in multiple statements, the amount of code saved is considerable. In addition, if document. getelementbyid ("...") is to be modified, only one statement on the front can be modified. Then rewrite it:

VaR obox1 = Document. getelementbyid ("textbox1 ");
VaR obox2 = Document. getelementbyid ("textbox2 ");
Obox2.value = obox1.value;

However, it is strange that the program does not achieve the expected results after execution.

Originally, obox2 itself is an object reference type. To assign a value to its attributes, you must initialize it before using it. Use the following code:

VaR obox1 = Document. getelementbyid ("textbox1 ");
VaR obox2 = new object (); // declare object variables
Obox2 = Document. getelementbyid ("textbox2 ");
Obox2.value = obox1.value;

-- Computer Learning Network (http://www.why100000.com)
2007-4-8

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.