Developer Forums | About Us | Site Map


Useful Lists

Web Host
site hosted by netplex

Online Manuals

JavaScript and the Document Object Model
By Nicholas Chase - 2004-03-10 Page:  1 2 3 4 5 6 7 8

The DHTML way

Using DHTML, you can access the information in a form field, or even change it. For example, you can create a script that increments the current form value by 1, then tell the page to execute the script when the user presses the button:

Listing 2. Incrementing the current number

    <title>Getting Sticky</title>
    <style type="text/css">
      * {font-family: sans-serif}
      a {font-size: 6pt}
      .editButton {font-size:6pt}

    <script type="text/javascript">
      function incrementCurrent() {
        current = parseInt(document.forms["noteForm"].total.value);
        document.forms["noteForm"].total.value = current + 1;

    <div id="mainDiv" style="height:95%; width:95%; border:3px solid red; 
                                                           padding: 10px;">
       <h1>Getting Sticky</h1>

       <form id="noteForm">
           Current number of notes:
                      <input type="text" name="total" value="0" size="3"/>
           <input type="button" value="Add a new note" 


In Listing 2, the incrementCurrent() function takes the document object, and then pulls the noteForm object out of the array of forms within the page. From the noteForm object, the function gets the form field named total and retrieves the value. It then updates this value within the page.

These kinds of changes are live. If you make the changes to the page, reload, and press the button repeatedly, you'll see that the text field is updated each time.

Similarly, you can retrieve the text of the div element using DHTML properties. Because it has an id of mainDiv, you could use the property innerHTML, as in:

theText = mainDiv.innerHTML;

In this case, you see two DHTML techniques: the forms array, and calling elements by names based on attribute values, rather than by element names or by overall structure. The problem here is that it doesn't lend itself well to generalization. Yes, you can use a variable for the name of the form, but what if an alternate presentation doesn't actually use a form?

View JavaScript and the Document Object Model Discussion

Page:  1 2 3 4 5 6 7 8 Next Page: DOM and JavaScript

First published by IBM developerWorks

Copyright 2004-2019 All rights reserved.
Article copyright and all rights retained by the author.