• Aucun résultat trouvé

Using JavaScript to Change Values in Form Fields

Dans le document Guide to HTML, JavaScript and PHP (Page 119-122)

In an interactive environment, you would like to be able to calculate new values based on  user input. HTML form fields can serve both purposes: users can enter values and the  document  can  use  JavaScript  to  calculate  new  values  for  other  fields.  Consider  this  problem:

Atmospheric pressure decreases with elevation. When barometric pressure is given in  weather reports, it is always referenced to sea level. (Otherwise it wouldn’t be possible  to draw weather maps that show the movement of air masses.) Scientists often need to  know the actual barometric pressure at a site. This is called station pressure. An approx-imate conversion from sea level pressure to station pressure is:

Pstation = Psea level − h/9.2

where pressure P is expressed in millibars and elevation h is expressed in meters.

U.S.  users  will  need  to  convert  from  inches  of  mercury  to  millibars: Pmillibars =   33.864 • Pinches of Hg. Write an application that calculates station pressure from sea level  pressure and elevation.

Document 4.11 demonstrates several new HTML and JavaScript features.

Document 4.11 (stationPressure.htm)

<html>

<head>

<title>Convert sea level pressure to station pressure.</title>

<font size="+1">

<b>Convert sea level pressure to station pressure (true pressure)</b></font><br /><br />

105 4.9 Using JavaScript to Change Values in Form Fields

</head>

<body bgcolor="lightblue">

This application converts sea level pressure to station pressure.<br />

Station pressure is the actual pressure at an observer's observing site.<br />

It is always less than or equal to sea level pressure (unless you are below<br />

sea level).

<br />

<form>

Fill in elevation and sea-level pressure:

<input type="text" name="elevation" value="0" size="8"

maxlength="7" /> (m)

<input type="text" name="sea_level_pressure" value="1013.25"

size="8" maxlength="7" /> (mbar) <br />

<input type="button" name="Calculate"

value="Click here to get station pressure:"

onclick="result.value=

parseFloat(sea_level_pressure.value)- parseFloat(elevation.value)/9.2;" />

input type="text" name="result" size="8"

maxlength="7" /> (mbar)<br />

<input type="reset" value="Reset all fields." />

</form>

</body>

</html>

The HTML code in Document 4.11 provides default values for the input fields. The  output reproduced here is for these default values.

Earlier discussions noted that JavaScript script was often, but not always, contained  within a script element in the head of a document. But, Document 4.11 shows that  JavaScript  statements  can  appear  in  a  document  without  a script  element.  It  is  not 

106 4 Fundamentals of the JavaScript Language

4

 obvious that this should be so—you could easily imagine a scenario in which JavaScript  statements were allowed to exist only inside a script element.

The "button" field allows a user to initiate an action by clicking anywhere on the  button. In this case, a click initiates the calculation of station pressure based on the values  currently  in  the elevation  and sea_level_pressure  fields—either  the  default  values or new values entered by the user. In order to respond to a moving a mouse cursor  over the button field and clicking, HTML uses an event handler, an important means of  providing interaction between a document and its user. Event handlers are attributes (of  input) whose “values” consist of a set of JavaScript instructions enclosed in quotes. 

There are several event handlers, but in this chapter only onclick will be used. (We will  return to the topic of event handlers in Chap. 6.) In Document 4.11, the event to be “han-dled” is a click of a mouse when its cursor is somewhere in the screen space defined by the 

“Click here to get station pressure” button.

How is information transmitted from a form field to JavaScript? It will not work to use,  for  example,  just  the elevation  name  from  the  form  field.  Why  not?  Because   elevation is just the name 

of  the  field,  not  its value. 

Form  fields  have  attributes,  such as name , and those attri-butes  have  values,  such  as  elevation.  The  attributes  have  values,  too,  accessed  through  the  “dot  notation” 

shown. One of the values of a field name is its defaultValue, which is the value  originally  assigned to the form field in the HTML document; this value can be left blank.

Of interest here is value, either the same as defaultValue or a new value entered  by the user. It is the value attribute that provides the input for a calculation and will  also  receive  calculated  results  in  other  form  fields.  Applying  the parseFloat (elevation.value) method translates the text in value into a numerical value. 

Using just elevation as the argument for parseFloat() makes no sense at all  from  JavaScript’s  point  of  view.  It  may  seem  cumbersome  to  use  this  notation,  but  remember that the name assigned to an HTML form field is simply not the same thing as  an identifier in JavaScript.

Once a mouse is clicked over the button field in Document 4.11, the JavaScript  statement  is  executed.  The  application  of parseFloat()  to  the  values  in  the elevation  and  sea_level_pressure fields is required for the same reasons previously discussed  for numerical values entered through prompt() . The distinction between text and numeri-cal values is easy to forget because JavaScript often applies type conversions to text values,  on its own. In Document 4.11, the calculation for the result field could also be written as result.value = sea_level_pressure.value –

elevation.value/9.2; // Bad idea!

However, if you replace the “-” sign with a “+” sign, the numerical calculation will not be  done! (Try it and see.) What is the difference? The “+” operator has a specific meaning when  applied to strings (it is interpreted as a concatenation operator), but the “-” operator does not. 

107 4.10 More Examples

When it encounters a subtraction operator, JavaScript is “smart enough” to understand that  the text values must be converted to numbers in order to carry out the specified action but,  from JavaScript’s point of view, this is not necessary for the “addition” operator.

Type conversion issues also apply when results of a numerical operation are assigned to  a form field name. Although result.value=…  looks like an assignment of one numeri-cal value to another, the numerical result must actually be converted back to text before it  can be assigned to result.value. You might think that some kind of “convert this  number to text” method is required, and in some sense it is, but you don’t have to specify  this conversion in your script because JavaScript automatically does it for you.

Finally, clicking anywhere on the “Reset all fields” button sets all inputs back to their  original values. JavaScript does this by accessing the defaultValue assigned to each  field.

4.10

Dans le document Guide to HTML, JavaScript and PHP (Page 119-122)