15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

onChange<br />

Chapter 9 ✦ Text-Related Form Objects (Chapter 25)<br />

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5<br />

Compatibility ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓<br />

Example<br />

Whenever a user makes a change to the text in a field in Listing 25-6 and then<br />

either tabs or clicks out of the field, the change event is sent to that field, triggering<br />

the onChange event handler.<br />

Because the form in Listing 25-6 has only one field, the example demonstrates a<br />

technique you can use that prevents a form from being “submitted” if the user accidentally<br />

presses the Enter key. The technique is as simple as defeating the submission<br />

via the onSubmit event handler of the form. At the same time, the onSubmit<br />

event handler invokes the checkIt() function, so that pressing the Enter key (as<br />

well as pressing Tab or clicking outside the field) triggers the function.<br />

Listing 25-6: Data Validation via an onChange event Handler<br />

<br />

<br />

Text Object Select/Focus<br />

<br />

// general purpose function to see if a suspected numeric input is a number<br />

function isNumber(inputStr) {<br />

for (var i = 0; i < inputStr.length; i++) {<br />

var oneChar = inputStr.substring(i, i + 1)<br />

if (oneChar < “0” || oneChar > “9”) {<br />

alert(“Please make sure entries are numbers only.”)<br />

return false<br />

}<br />

}<br />

return true<br />

}<br />

function checkIt(form) {<br />

inputStr = form.numeric.value<br />

if (isNumber(inputStr)) {<br />

// statements if true<br />

} else {<br />

form.numeric.focus()<br />

form.numeric.select()<br />

}<br />

}<br />

<br />

<br />

<br />

Continued<br />

367<br />

document.formObject.textObject.onChange

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

Saved successfully!

Ooh no, something went wrong!