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 />

the second text box, the focus moves to the third. This “ tab forward ” behavior can be accomplished<br />

using the following code:<br />

(function(){<br />

function tabForward(event){<br />

event = EventUtil.getEvent(event);<br />

var target = EventUtil.getTarget(event);<br />

if (target.value.length == target.maxLength){<br />

var form = target.form;<br />

}<br />

}<br />

for (var i=0, len=form.elements.length; i < len; i++) {<br />

if (form.elements[i] == target) {<br />

form.elements[i+1].focus();<br />

return;<br />

}<br />

}<br />

})();<br />

var textbox1 = document.getElementById(“txtTel1”);<br />

var textbox2 = document.getElementById(“txtTel2”);<br />

var textbox3 = document.getElementById(“txtTel3”);<br />

EventUtil.addHandler(textbox1, “keyup”, tabForward);<br />

EventUtil.addHandler(textbox2, “keyup”, tabForward);<br />

EventUtil.addHandler(textbox3, “keyup”, tabForward);<br />

The tabForward() function is the key to this functionality. It checks to see if the text box ’ s maximum<br />

length has been reached by comparing the value to the maxlength attribute. If they ’ re equal (since the<br />

browser enforces the maximum, there ’ s no way it could be more), then the next form element needs to be<br />

found by looping through the elements collection until the text box is found, and then setting focus to<br />

the element in the next position. This function is then assigned as the onkeyup handler for each text box.<br />

Since the keyup event fires after a new character has been inserted into the text box, this is the ideal time<br />

to check the length of the text - box contents. When filling out this simple form, the user will never have to<br />

press the Tab key to move between fields and submit the form.<br />

Scripting Select Boxes<br />

Select boxes are created using the < select > and < option > elements. To allow for easier interaction with<br />

the control, the HTMLSelectElement type provides the following properties and methods in addition to<br />

those that are available on all form fields:<br />

❑<br />

❑<br />

add(newOption, relOption) — Adds a new < option > element to the control before the<br />

related option.<br />

multiple — A Boolean value indicating if multiple selections are allowed; equivalent to the<br />

HTML multiple attribute.<br />

450

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

Saved successfully!

Ooh no, something went wrong!