10.07.2017 Views

246996016-HTML5-Step-by-Step

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

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

JavaScript Events and jQuery 301<br />

});<br />

<br />

<br />

<br />

The code introduces a few new concepts, namely the if conditional. In this case, the code<br />

uses the if conditional to test whether the value entered <strong>by</strong> the user matches what you’re<br />

expecting from the text field on the form. The jQuery .val() function in the preceding<br />

code is also new here. The .val() function obtains the value of whatever has been entered<br />

into the text box (or whatever element has been selected). Finally, when the text box is<br />

not filled in correctly, there’s a return false; statement. In this context, return false; indicates<br />

that processing of the Web form should not continue, and the form should not be<br />

submitted.<br />

When submitted with a value of Yes in the text box, the code displays an alert and continues<br />

with form submission. If the user enters anything else and submits the form, the<br />

validation code displays an alert indicating that the form wasn’t filled in correctly, and<br />

halts form submission to the server <strong>by</strong> returning false.<br />

A more complex yet more user-friendly approach for handling errors is to change the<br />

background color on the form field that was filled in incorrectly. Obviously, for the one<br />

field form in this example, it’s clear which field is incorrect. But on a more complex form,<br />

it may not be as obvious which field contains an incorrect value. Here’s the code to<br />

change the background color:<br />

$("#myForm").submit(function() {<br />

if ($("#firstName").val() == "Yes") {<br />

alert("Form entered correctly");<br />

} else {<br />

$("#firstName").css("backgroundColor","red");<br />

return false;<br />

}<br />

});<br />

This code changes the backgroundColor of the form element identified <strong>by</strong> the id first<br />

Name to red when filled in incorrectly. However, best practice dictates not changing CSS<br />

style information within JavaScript code. It’s much better to add and remove CSS styles<br />

from elements. Doing so makes troubleshooting easier and results in cleaner code all<br />

around.<br />

jQuery has functions to add and remove CSS classes from elements: the aptly titled .<br />

addClass() and .removeClass() functions. On form validation pages, I’ll typically create a<br />

CSS error class that sets the background color to a red (or a reddish color that attracts<br />

attention).

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

Saved successfully!

Ooh no, something went wrong!