29.07.2016 Views

front-end-developer_1_

Create successful ePaper yourself

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

Front-End-Developer - Level 1<br />

Here, we've used the && (and) operator. The expression g<strong>end</strong>er === 'male' && age < 26<br />

only evaluates to true if both conditions evaluate to true . You can try it out in the<br />

JavaScript console to see for yourself.<br />

If we decide that we actually want to charge the premium to all men, and to anyone who's<br />

under 26, we can use the || (or) operator:<br />

scripts.js<br />

if (g<strong>end</strong>er === 'male' || age < 26) {<br />

}<br />

quote += 50;<br />

The expression g<strong>end</strong>er === 'male' || age < 26 evaluates to true if either condition<br />

evaluates to true .<br />

One thing I don't like about our page is that it doesn't give an error if the user forgets to enter<br />

their age - it just treats it like their age is 0. Let's give an error if they leave the age field<br />

blank:<br />

scripts.js<br />

$(document).ready(function() {<br />

$("form#insurance").submit(function(event) {<br />

var age = parseInt($("input#age").val());<br />

var g<strong>end</strong>er = $("select#g<strong>end</strong>er").val();<br />

if (age) {<br />

var quote = (100 - age) * 3;<br />

if (g<strong>end</strong>er === 'male' && age < 26) {<br />

quote += 50;<br />

}<br />

$("#rate").empty().app<strong>end</strong>(quote);<br />

$("#quote").show();<br />

} else {<br />

alert('Please enter your age.');<br />

}<br />

});<br />

});<br />

event.preventDefault();<br />

Does this strike you as a little funny? Before now, all of the conditions for our if<br />

statements have evaluated to booleans. This time, we're looking at a string. If the user<br />

doesn't input a value, jQuery will return an empty string (with the car insurance page open,<br />

More Branching<br />

127

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

Saved successfully!

Ooh no, something went wrong!