CSCI 101: Intro to Computer Science

Lab 5.3:   Form Processing with JavaScript

Many JavaScript events can be called from the form elements. All these elements should be put in HTML between the opening <form> and closing </form> tags. These elements provide interactive interface with the user and usually start with the tag <input> which has no closing one. The form input elements are specified by describing their type within the <input> tag. For example, to get the following button with the word Text on it

the following code can be used:

<input type="button" value="Switch">

If you click this button it changes its form. All these features are provided by your browser.

  1. If you put the mouse cursor over the button below then nothing will happen. Click the button with the left mouse button. As you see, the event handler onClick is used to achieve this behavior.

         

    This event handler can be used in HTML as follows:

    <img src="ballred.gif"> <img src="ballblue.gif"> <p>
    <input type="button" value="Switch" onclick="LampSwitch()">
    

    As you probably already understand, this event handler calls the function LampSwitch() that actually changes the ball colors. The function has to swap the images of the blue and the red balls as soon as the button is clicked. The ball images have numbers 0 and 1. Note that the buttons, being the form elements, are NOT images, so they are NOT counted in the image list by the browser.

    function LampSwitch()
    {
       var temp = document.images[0].src;
       document.images[0].src = document.images[1].src;
       document.images[1].src = temp;
    }
    

    In the first line of this function we introduce a temporary variable temp that stores the file name of the red ball image.

  2. Consider various applications of the ONCLICK event handler and try to achieve a similar behavior by yourself. Make sure to check the source of this webpage.

  3. Processing of selection lists of forms is a bit more complicated. First, try to change the background color of this document by choosing it from the list with the left mouse button:

    The corresponding HTML looks as follows:

    <select name="selectC" size="1" onchange="PickColor(this)">
       <option>orange</option>
       <option>violet</option>
       <option>white</option>
       <option>green</option>
       <option>#33CC55</option>
       <option>blue</option>
    </select>
    

    The event handler onchange calls the function PickColor(this.form) with a "strange" parameter this. The reason for this parameter is that we need to access several lists associated with our form. A document might contain several forms and for each form the lists of their elements are disjoint. The function, therefore needs to know which form should it work with. The forms of any document may have their names to distinguish them one from another. An alternative solution is to pass the "current" element to the function, i.e. the selection list element that we are working with. The function PickColor works with the selection list specified in its parameter:

    function PickColor(list)
    {
       var sIndex = list.selectedIndex;
       var sColor = list.options[sIndex].text;
       document.bgColor = sColor;
    }
    

    First it extracts the index of the choice from the selection list and in the second line the string corresponding to this index is created. The string contains just the color name that is passed to the corresponding attribute of the document in the third line.

  4. The next script is the most complicated one. However, it is a significant simplification of the corresponding script from the text book. Try to figure out how does it work by playing with it and checking its source. Please also refer to its description in the book.

  5. The last example is a combination of JavaScript and CGI script. CGI scripts are not a part of our course. However, just for your information CGI script is a special program that runs on a server side. This program gets the information from your local machine (usually it is a form), processes it and returns you the results. These results are displayed by your browser.

    The program can, for example, check if the form is filled out correctly, or at least all necessary information (e.g. the name) is given by the user. If it is not the case, the CGI script asks to provide missing information. If the information is complete, the CGI script can put it into a list for further processing.

    Therefore, if the user provided an incomplete information, then sending the messages back and force between your machine and the server produces a non-necessary network traffic. It would be nice to make all checking on your local machine without bothering the network. If the user's information satisfy some criterion it should be submitted to the server for further processing. It is possible to check out the form by using JavaScript.

    The form asks the user name and the age. If you leaved the name field blank you get a warning. The information will not be sent to the server without filling up this field. Furthermore, if the entered age is below 18, the information also will not be further processed. Finally, if the user name is entered and the user's age is at least 18, this information is forwarded to a server that greets the user. Try it.

    We do not consider here the program responsible for greeting the user. Our goal is to understand some basics of form processing. The form itself is not too complicated:

    Your name:
    Your age:    

       

    It uses four input form elements: two text fields and two buttons. The text fields have their own names: NameBox and AgeBox. Furthermore, the form itself has a name userData. These names are necessary for the form processing with JavaScript. The &nbsp; instruction provides a small horizontal space between the buttons.

    <form Name="userData" method="get" 
          action="http://cs2.uwsuper.edu/cgi-bin/sb/name" 
          onsubmit="return CheckForm()"> 
    
    Your name: <input type="text" name="NameBox"> <br>
    Your age:  <input type="text" name="AgeBox">  
    <p>
    <input type="submit" value="Submit"> &nbsp; &nbsp;
    <input type="reset" value="Reset">
    </form>
    

    The second line in the form declaration that starts with "METHOD ..." is necessary for establishing a link between the local machine and the server and passing the form data there. It is not relevant for our course. The form processing is done by calling the function CheckForm() by the onsubmit event handler. The function CheckForm() returns a logical value (true or false) as the result of form checking. This value is used by the event handler to pass the form data to the server. The data will be passed only if the returned value by the CheckForm() function is true.

    function CheckForm()
    {
      var name = document.userData.NameBox.value;
      var age  = document.userData.AgeBox.value;
    
      if ((name == null) || (name == ""))
      {
        alert("Please enter your name");
        document.userData.NameBox.focus();
        document.userData.NameBox.select();
        return false;
      }
    
      if ((age == null) || (age == ""))
      {
        alert("Please enter your age");
        document.userData.AgeBox.focus();
        document.userData.AgeBox.select();
        return false;
      }
    
      if (age < 18)
      {
        alert("You have to be at least 18 years old to continue");
        return false;
      }
    
      alert("Thank you for submission");
      return true;
    }
    

    In the two first lines the text form the input form fields NameBox and AgeBox is extracted to the variables name and age respectively. For this the form name userData is also used.

    The first if statement checks whether the name field was clicked at all and whether a name is entered. If it is not the case then the alert window "Please enter your name" is popping up and the cursor is put into the name input box, which is also activated preparing for the user input. In this case the result of checking is false, which is returned back to the calling program (in this case the onsubmit event handler).

    The second if statement makes a similar checking of the age string. Finally, the last if statement checks whether the entered age is at least 18. If all form filling conditions are satisfied, i.e. if some name and age are entered and the age is at least 18 then the function returns true as the result of form checking. In this case the onsubmit event handler passed all the entered data to the server for further processing there.

    For simplicity we did not check whether the entered age data is a number at all. It is it an arbitrary string (for example "zzz"), then our script accepts is as a valid data. To implement this checking one can use the methods described in the text book.