Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Obtaining User Input with prompt Dialogs - JavaScript(JS)

Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Introduction to Scripting

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Obtaining User Input with prompt Dialogs - JavaScript(JS)

Scripting gives you the ability to generate part or all of a web page’s content at the time it is shown to the user.

Obtaining User Input with prompt Dialogs

 

Scripting gives you the ability to generate part or all of a web page’s content at the time it is shown to the user. A script can adapt the content based on input from the user or other variables, such as the time of day or the type of browser used by the client. Such web pages are said to be dynamic, as opposed to static, since their content has the ability to change. The next two subsections use scripts to demonstrate dynamic web pages.

 

1. Dynamic Welcome Page

 

Our next script builds on prior scripts to create a dynamic welcome page that obtains the user’s name, then displays it on the page. The script uses another predefined dialog box from the window object—a prompt dialog—which allows the user to input a value that the script can use. The program asks the user to input a name, then displays the name in the XHTML document. Figure 6.7 presents the script and sample output. [Note: In later Java-Script chapters, we obtain input via GUI components in XHTML forms, as introduced in Chapter 4.]

 

Line 12 is a declaration that contains the JavaScript keyword var. Keywords are words that have special meaning in JavaScript. The keyword var at the beginning of the statement indicates that the word name is a variable. A variable is a location in the com-puter’s memory where a value can be stored for use by a program. All variables have a name, type and value, and should be declared with a var statement before they are used in

 

    <?xml version = "1.0" encoding = "utf-8"?>

 

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

    <!-- Fig. 6.7: welcome5.html -->

 

    <!-- Prompt box used on a welcome screen. -->

 

    <html xmlns = "http://www.w3.org/1999/xhtml">

 

    <head>

 

    <title>Using Prompt and Alert Boxes</title>

 

      <script type = "text/javascript">

      <!--

 

      var name; // string entered by the user

 

      // read the name from the prompt box as a string

 

      name = window.prompt( "Please enter your name" );

 

                 document.writeln( "<h1>Hello, " + name +

 

      ", welcome to JavaScript programming!</h1>" );

      // -->

 

      </script>

 

      </head>

 

      <body>

 

      <p>Click Refresh (or Reload) to run this script again.</p>

 

      </body>

 

</html>


Fig. 6.7 | Prompt box used on a welcome screen.

 

a program. Although using var to declare variables is not required, we will see in Chapter 9, JavaScript: Functions, that var sometimes ensures proper behavior of a script.

 

The name of a variable can be any valid identifier. An identifier is a series of characters consisting of letters, digits, underscores ( _ ) and dollar signs ($) that does not begin with a digit and is not a reserved JavaScript keyword. [Note: A complete list of keywords can be found in Fig. 7.2.] Identifiers may not contain spaces. Some valid identifiers are Welcome, $value, _value, m_inputField1 and button7. The name 7button is not a valid identifier, because it begins with a digit, and the name input field is not valid, because it contains a space. Remember that JavaScript is case sensitive—uppercase and lowercase letters are considered to be different characters, so name, Name and NAME are different identifiers.

Declarations end with a semicolon (;) and can be split over several lines with each variable in the declaration separated by a comma—known as a comma-separated list of variable names. Several variables may be declared either in one declaration or in multiple declarations.

 

Programmers often indicate the purpose of each variable in the program by placing a JavaScript comment at the end of each line in the declaration. In line 12, a single-line comment that begins with the characters // states the purpose of the variable in the script. This form of comment is called a single-line comment because it terminates at the end of the line in which it appears. A // comment can begin at any position in a line of JavaScript code and continues until the end of the line. Comments do not cause the browser to per-form any action when the script is interpreted; rather, comments are ignored by the Java-Script interpreter.

Another comment notation facilitates the writing of multiline comments. For example,

 

/*      This is a multiline comment. It can be

 

split over many lines. */

 

is a multiline comment spread over several lines. Such comments begin with the delimiter /* and end with the delimiter */. All text between the delimiters of the comment is ig-nored by the interpreter.

JavaScript adopted comments delimited with /* and */ from the C programming lan-guage and single-line comments delimited with // from the C++ programming language. JavaScript programmers generally prefer C++-style single-line comments over C-style comments. Throughout this book, we use C++-style single-line comments.

 

Line 14 is a comment indicating the purpose of the statement in the next line. Line 15 calls the window object’s prompt method, which displays the dialog in Fig. 6.8. The dialog allows the user to enter a string representing the user’s name.

 

The argument to prompt specifies a message telling the user what to type in the text field. This message is called a prompt because it directs the user to take a specific action. An optional second argument, separated from the first by a comma, may specify the default string displayed in the text field; our code does not supply a second argument. In this case, Internet Explorer displays the default value undefined, while Firefox and most other browsers leave the text field empty. The user types characters in the text field, then clicks the OK button to submit the string to the program. We normally receive input from a user through a GUI component such as the prompt dialog, as in this program, or through an XHTML form GUI component, as we will see in later chapters.

 

The user can type anything in the text field of the prompt dialog. For this program, whatever the user enters is considered the name. If the user clicks the Cancel button, no string value is sent to the program. Instead, the prompt dialog submits the value null, a JavaScript keyword signifying that a variable has no value. Note that null is not a string literal, but rather a predefined term indicating the absence of value. Writing a null value to the document, however, displays the word null in the web page.

 

The statement in line 15 assigns the value returned by the window object’s prompt method (a string containing the characters typed by the user—or the default value or null if the Cancel button is clicked) to variable name by using the assignment operator, =. The statement is read as, “name gets the value returned by window.prompt( "Please enter your name" ).” The = operator is called a binary operator because it has two operandsname and the result of the expression window.prompt( "Please enter your name" ). This entire statement is called an assignment statement because it assigns a value to a variable. The expression to the right of the assignment operator is always evaluated first.


Lines 17–18 use document.writeln to display the new welcome message. The expres-sion inside the parentheses uses the operator + to “add” a string (the literal "<h1>Hello, "), the variable name (the string that the user entered in line 15) and another string (the literal ", welcome to JavaScript programming!</h1>"). JavaScript has a version of the + operator for string concatenation that enables a string and a value of another data type (including another string) to be combined. The result of this operation is a new (and nor-mally longer) string. If we assume that name contains the string literal "Jim", the expres-sion evaluates as follows: JavaScript determines that the two operands of the first + operator (the string "<h1>Hello, " and the value of variable name) are both strings, then concatenates the two into one string. Next, JavaScript determines that the two operands of the second + operator (the result of the first concatenation operation, the string"<h1>Hello, Jim", and the string ", welcome to JavaScript programming!</h1>") are both strings and concatenates the two. This results in the string "<h1>Hello, Jim, welcome to JavaScript programming!</h1>". The browser renders this string as part of the XHTML document. Note that the space between Hello, and Jim is part of the string "<h1>Hello, ".

 

As we’ll illustrate later, the + operator used for string concatenation can convert other variable types to strings if necessary. Because string concatenation occurs between two strings, JavaScript must convert other variable types to strings before it can proceed with the operation. For example, if a variable age has an integer value equal to 21, then the expression "my age is " + age evaluates to the string "my age is 21". JavaScript converts the value of age to a string and concatenates it with the existing string literal "my age is ". After the browser interprets the <head> section of the XHTML document (which contains the JavaScript), it then interprets the <body> of the XHTML document (lines 22–24) and renders the XHTML. Notice that the XHTML page is not rendered until the prompt is dismissed because the prompt pauses execution in the head, before the body is processed. If you click your browser’s Refresh (Internet Explorer) or Reload (Firefox) button after entering a name, the browser will reload the XHTML document, so that you can execute the script again and change the name. [Note: In some cases, it may be necessary to hold down the Shift key while clicking the Refresh or Reload button, to ensure that the XHTML document reloads properly. Browsers often save a recent copy of a page in memory, and holding the Shift key forces the browser to download the most recent version of a page.]

 

 

2. Adding Integers

 

Our next script illustrates another use of prompt dialogs to obtain input from the user. Figure 6.9 inputs two integers (whole numbers, such as 7, –11, 0 and 31914) typed by a user at the keyboard, computes the sum of the values and displays the result.

 

Lines 12–16 declare the variables firstNumber, secondNumber, number1, number2 and sum. Single-line comments state the purpose of each of these variables. Line 19 employs a prompt dialog to allow the user to enter a string representing the first of the two

 

      <?xml version = "1.0" encoding = "utf-8"?>

 

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

      <!-- Fig. 6.9: addition.html -->

 

      <!-- Addition script. -->

 

      <html xmlns = "http://www.w3.org/1999/xhtml">

 

      <head>

 

      <title>An Addition Program</title>

 

        <script type = "text/javascript">

        <!--

 

        var firstNumber; // first string entered by user

 

        var secondNumber; // second string entered by user

 

        var number1; // first number to add

 

        var number2; // second number to add

 

        var sum; // sum of number1 and number2

        // read in first number from user as a string

 

        firstNumber = window.prompt( "Enter first integer" );

 

        // read in second number from user as a string

 

        secondNumber = window.prompt( "Enter second integer" );

 

        // convert numbers from strings to integers

 

        number1 = parseInt( firstNumber );

 

        number2 = parseInt( secondNumber );

                 sum = number1 + number2; // add the numbers

 

        // display the results

 

        document.writeln( "<h1>The sum is " + sum + "</h1>" );

        // -->

 

        </script>

 

        </head>

 

        <body>

 

        <p>Click Refresh (or Reload) to run the script again</p>

 

        </body>

 

</html>



Fig. 6.9 | Addition script.

 

integers that will be added. The script assigns the first value entered by the user to the vari-able firstNumber. Line 22 displays a prompt dialog to obtain the second number to add and assign this value to the variable secondNumber.

 

As in the preceding example, the user can type anything in the prompt dialog. For this program, if the user either types a noninteger value or clicks the Cancel button, a logic error will occur, and the sum of the two values will appear in the XHTML document as NaN (meaning not a number). A logic error is caused by syntactically correct code that produces an undesired result. In Chapter 11, JavaScript: Objects, we discuss the Number object and its methods that can determine whether a value is not a number.

 

Recall that a prompt dialog returns to the program as a string the value typed by the user. Lines 25–26 convert the two strings input by the user to integer values that can be used in a calculation. Function parseInt converts its string argument to an integer. Line 25 assigns to the variable number1 the integer that function parseInt returns. Line 26 assigns an integer value to variable number2 in a similar manner. Any subsequent references to number1 and number2 in the program use these integer values. [Note: We refer to parseInt as a function rather than a method because we do not precede the function call with an object name (such as document or window) and a dot (.). The term method means that the function belongs to a particular object. For example, method writeln belongs to the document object and method prompt belongs to the window object.]

 

Line 28 calculates the sum of the variables number1 and number2 using the addition operator, +, and assigns the result to variable sum by using the assignment operator, =. Notice that the + operator can perform both addition and string concatenation. In this case, the + operator performs addition, because both operands contain integers. After line 28 performs this calculation, line 31 uses document.writeln to display the result of the addition on the web page. Lines 33 and 34 close the script and head elements, respec-tively. Lines 35–37 render the body of XHTML document. Use your browser’s Refresh or Reload button to reload the XHTML document and run the script again.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.