04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 13: Scripting Forms<br />

});<br />

target.style.backgroundColor = “red”;<br />

} else {<br />

target.style.backgroundColor = “”;<br />

}<br />

The onfocus event handler simply changes the background color of the text box to yellow, more clearly<br />

indicating that it ’ s the active field. The onblur and onchange event handlers turn the background color<br />

red if any non - numeric character is found. To test for a non - numeric character, a simple regular<br />

expression is used against the text box ’ s value . This functionality has to be in both the onblur and<br />

onchange event handlers to ensure that the behavior remains consistent regardless of text - box changes.<br />

The relationship between the blur and change events is not strictly defined. In<br />

some browsers, the blur event fires before change ; in others, it ’ s the opposite. You<br />

can ’ t depend on the order in which these events fire, so use care whenever they are<br />

required.<br />

Scripting Text Boxes<br />

There are two ways to represent text boxes in HTML: a single - line version using the < input > element<br />

and a multiline version using < textarea > . These two controls are very similar and behave in similar<br />

ways most of the time. There are, however, some important differences.<br />

The < input > element must have its type attribute set to “ text ” to display a text box. The size<br />

attribute can then be used to specify how wide the text box should be in terms of visible characters.<br />

The value attribute specifies the initial value of the text box, and the maxlength attribute specifies the<br />

maximum number of characters allowed in the text box. So to create a text box that can display<br />

25 characters at a time but has a maximum length of 50, the following code can be used:<br />

< input type=”text” size=”25” maxlength=”50” value=”initial value” ><br />

The < textarea > element always renders a multiline text box. To specify how large the text box should<br />

be, you can use the rows attribute, which specifies the height of the text box in number of characters, and<br />

the cols attribute, which specifies the width in number of characters, similar to size for an < input ><br />

element. Unlike < input > , the initial value of a < textarea > must be enclosed between < textarea > and<br />

< /textarea > , as shown here:<br />

< textarea rows=”25” cols=”5” > initial value < /textarea ><br />

Also unlike the < input > element, a < textarea > cannot specify the maximum number of characters<br />

allowed using HTML.<br />

441

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!