Introduction to Conditions

Introduction

A comparison is an operation that establishes a relationship between two values. The operation is made to find out whether two values are the same, two variables hold the same value, one value is higher than the other, the value of a variable is higher than a referenced value. The comparison can be performed on numbers, strings, etc. To give you the ability to perform comparisons, JavaScript support various operators referred to as Boolean operators. The operators can be used in your TypeScript code.

Practical LearningPractical Learning: Introducing Conditional Statements

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the middle frame of the New Project dialog box, make sure ASP.NET Web Application (.NET Framework) is selected.
    Change the Name to PayrollPreparation5
  4. Click OK
  5. In the ASP.NET Web Application dialog box, make sure the MVC icon is selected.
    Click OK
  6. In the Solution Explorer, right-click Content -> Add -> New Item...
  7. In the left list of the Add New Item dialog box, under Visual C#, expand Web, and click Markup
  8. In the middle list, click Style Sheet
  9. Change the file Name to PayrollPreparation
  10. Click Add
  11. Change the document as follows:
    body {
        background-color: white;
    }
    
    .bold        { font-weight: 600;   }
    .small       { width:       100px; }
    .large-text  { width:       120px; }
    .delimiter   { margin:      auto;
                   width:       700px; }
    .common-font { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  12. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  13. Change the document as follows:
    using System.Web.Optimization;
    
    namespace PayrollPreparation5
    {
        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css",
                          "~/Content/PayrollPreparation.css"));
            }
        }
    }
  14. In the Solution Explorer, right-click Scripts -> Add -> New Item...
  15. In the left list of the New Item dialog box, under Visual C# and under Web, click Scripts
  16. In the middle list, click TypeScript File
  17. Change the file Name to TimeSheetEvaluation
  18. Click Add
  19. Change the document as follows:
    function evaluateDailySalary(day: string, salary: number, time: number) {
        let pay = function (x, y) { return x * y; }
    
        document.getElementById(day).innerHTML = pay(salary, time).toFixed(2);
    }
    
    function calculate() {
        const hSalary: number = Number((document.querySelector("#hourlySalary") as HTMLInputElement).value || 0);
        const mon: number = Number((document.querySelector("#monday") as HTMLInputElement).value || 0);
        const tue: number = Number((document.querySelector("#tuesday") as HTMLInputElement).value || 0);
        const wed: number = Number((document.querySelector("#wednesday") as HTMLInputElement).value || 0);
        const thu: number = Number((document.querySelector("#thursday") as HTMLInputElement).value || 0);
        const fri: number = Number((document.querySelector("#friday") as HTMLInputElement).value || 0);
    
        let multiplication: (x: number, y: number) => number = function (x: number, y: number) { return x * y; }
        let addition: (a: number, b: number, c: number, d: number, e: number) => number =
            function (a: number, b: number, c: number, d: number, e: number) { return a + b + c + d + e; }
    
        const weeklySalary: number = multiplication(addition(mon, tue, wed, thu, fri), hSalary);
    
        evaluateDailySalary("salaryMonday", hSalary, mon);
        evaluateDailySalary("salaryTuesday", hSalary, tue);
        evaluateDailySalary("salaryWednesday", hSalary, wed);
        evaluateDailySalary("salaryThursday", hSalary, thu);
        evaluateDailySalary("salaryFriday", hSalary, fri);
    
        let netPay: number;
    
        netPay = weeklySalary;
    
        document.getElementById("weeklySalary").innerHTML = netPay.toFixed(2);
    }
  20. In the Solution Explorer, right-click Scripts -> Add -> New Item...
  21. In the left frame of the Add New Item dialog box, under Visual C#, expand Web and click Scripts
  22. In the middle list, click TypeScript JSON Configuration File
  23. Accept the suggested name of the file, tsconfig.json, and click Add
  24. Change the document as follows:
    {
      "compilerOptions": {
        "noImplicitAny": false,
        "noEmitOnError": true,
        "removeComments": false,
        "sourceMap": true,
        "target": "es5"
      },
      "files": [
        "TimeSheetEvaluation.ts"
      ],
      "compileOnSave": true
    }
  25. In the Solution Explorer, expand Controllers, and click HomeController.cs
  26. In the class, create a method named PayrollEvaluation as follows:
    using System.Web.Mvc;
    
    namespace PayrollPreparation5.Controllers
    {
        public class HomeController : Controller
        {
            . . .
    
            public ActionResult PayrollEvaluation() => View();
        }
    }
  27. In the class, right-click PayrollEvaluation() -> Add View...
  28. Make sure the View Name text box is displaying PayrollEvaluation.
    Click Add
  29. Create a form as follows:
    @{
        ViewBag.Title = "Payroll Evaluation";
    }
    
    <h2 class="common-font text-center bold">Payroll Evaluation</h2>
    
    <hr />
    
    <div class="delimiter common-font">
        <form name="PayrollEvaluation" method="post">
            <table class="table table-striped">
                <tr>
                    <td class="large-text bold">Hourly Salary:</td>
                    <td><input class="form-control small" id="hourlySalary" /></td>
                    <td colspan="4">&nbsp;&nbsp;&nbsp;</td>
                </tr>
                <tr>
                    <td class="large-text bold">Days</td>
                    <td class="bold text-center">Monday</td>
                    <td class="bold text-center">Tuesday</td>
                    <td class="bold text-center">Wednesday</td>
                    <td class="bold text-center">Thursday</td>
                    <td class="bold text-center">Friday</td>
                </tr>
                <tr>
                    <td class="bold">Time Worked:</td>
                    <td><input type="number" class="form-control small" id="monday" /></td>
                    <td><input type="number" class="form-control small" id="tuesday" /></td>
                    <td><input type="number" class="form-control small" id="wednesday" /></td>
                    <td><input type="number" class="form-control small" id="thursday" /></td>
                    <td><input type="number" class="form-control small" id="friday" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td class="text-center" colspan="5">
                        <input type="button" id="btnCalculate" class="btn btn-primary"
                               style="width: 500px" value="Calculate" onclick="calculate()" />
                    </td>
                </tr>
                <tr>
                    <td class="bold">Daily Salary:</td>
                    <td><span id="salaryMonday"></span></td>
                    <td><span id="salaryTuesday"></span></td>
                    <td><span id="salaryWednesday"></span></td>
                    <td><span id="salaryThursday"></span></td>
                    <td><span id="salaryFriday"></span></td>
                </tr>
                <tr>
                    <td colspan="4">&nbsp;</td>
                    <td class="bold">Weekly Salary:</td>
                    <td><span id="weeklySalary"></span></td>
                </tr>
            </table>
        </form>
    </div>
    
    <script src="~/Scripts/TimeSheetEvaluation.js"></script>
  30. Press Ctrl + F5 to execute the application:

    Checking a Check Box

  31. In the text boxes, type the following values:
    Hourly Salary: 21.37
    Monday:        8.00
    Tuesday:       7.00
    Wednesday:     9.50
    Thursday:      7.50
    Friday:        9.00

    Checking a Check Box

  32. Click the Calculate button:

    Checking a Check Box

  33. Close the browser and return to your programming environment

Introduction to Comparisons

A comparison consists of finding the logical relationship between two constant values, the values of two variables, or a constant value and the value of a variable. To let you compare two values or objects for equality, JavaScript provides the === operator. It is used as in value1 === value2. If value1 and value2 are equal, the condition is true. Otherwise the condition is false.

If a Condition is True

To let you perform the most fundamental type of comparison, JavaScript provides a keyword named if. The primary formula to use it is:

if(condition) {
    statement;
}

The condition can be formulated a Boolean operation, such as variable-name === some-value. Here is an example:

TypeScript File: Examination.ts

let stopped: string = 'No';

if (stopped === "No") {
    document.querySelector("#amt").innerHTML = "40";
}

View: TrafficTicketAnalysis.cshtml

@{
    ViewBag.Title = "Traffic Ticket Analysis";
}

<h2>Traffic Ticket Analysis</h2>

<p><b>Did the driver stop at a Stop Sign?</b> No</p>
<p><b>Ticket Amount:</b> <span id="amt"></span></p>

<script src="~/Scripts/TicketEvaluation.js"></script>

This would produce:

If a Condition is True

The above formula is for a condition that needs only one statement. Otherwise, in the body delimited by curly brackets, you can write as many statements as you need. The formula would become:

if(condition) {
    statement_1
    statement_2;
    . . .
    statement_n;
}

Here is an example:

TypeScript File: Examination.ts

let stopped: string = 'No';

if (stopped === "No") {
    document.querySelector("#infractionTitle").innerHTML = "<b>Traffic Violation</b>: Failed to Stop at Red Light";
    document.querySelector("#description").innerHTML     = "<b>Description:</b> Our records indicate that your " +
                                                           "vehicle failed to stop at a red light before making " +
                                                           "a right turn. The law in our state indicates that if a " +
                                                           "vehicle that needs to make a right turn comes to a " +
                                                           "traffic light that has the Red Light On, the vehiche " +
                                                           "must first completely stop before making the right turn.";
    document.querySelector("#amt").innerHTML = "75";
}

View: TrafficTicketAnalysis.cshtml

@{
    ViewBag.Title = "Traffic Ticket Analysis";
}

<h2>Traffic Ticket Analysis</h2>

<p><b>Did the driver stop at a Right Turn Red Light?</b> No</p>

<p id="infractionTitle"></p>
<p id="description"></p>
<p><b>Ticket Amount:</b> <span id="amt"></span></p>

<script src="~/Scripts/TicketEvaluation.js"></script>

This would produce:

A Conditional Statement

Microsoft Visual Studio can also assist you in creating an if conditional statement. To do this, right-click the section of the Code Editor where you want to create it and click Insert Snippet... In the window that appears, double-click General. In the list that appears, double-click if.

Creating Multiple Statements

In your code, if you want to perform many comparisons, you can create as many conditions as you want. Each condition would use its own condition(s). The formula to follow would be:

if(condition1) {
	statement_1;
}

if(condition2) {
	statement_2;
}

. . .

if(condition_n)) {
	statement_n;
}

Of course, each condition can have as many statements as necessary.

Web Controls and Logical Operations

Introduction

Practically any Web control can be involved in a conditional statement. Some controls are better adapters while some others may require code.

A Check Box

A check is a small square that is checked or marked. If it was previously checked and it gets clicked, it would become unchecked or unmarked.

To get a check box, create an INPUT tag and set its TYPE attribute to CHECKBOX.

When creating a check box, to let you check the control, if the TYPE attribute of an INPUT tag is set to CHECKBOX, the INPUT tag is equipped with an attribute named CHECKED. The value of this attribute is Boolean. When the control is checked, its CHECKED attribute is TRUE. If the control is not checked, its CHECKED attribute is FALSE. At any time, to find out whether the control is currently checked, check the value of its CHECKED property.

Practical LearningPractical Learning: Checking a Check Box

  1. To create a check box, change the PayrollEvaluation.cshtml document as follows:
    @{
        ViewBag.Title = "Payroll Evaluation";
    }
    
    <h2 class="common-font text-center bold">Payroll Evaluation</h2>
    
    <hr />
    
    <div class="delimiter common-font">
        <form name="PayrollEvaluation" method="post">
            <table class="table table-striped">
                <tr>
                    <td class="large-text bold">Hourly Salary:</td>
                    <td><input class="form-control small" id="hourlySalary" /></td>
                    <td colspan="4"><label for="isMarried">Employee is Married</label>&nbsp;&nbsp;&nbsp;<input type="checkbox" id="isMarried" /></td>
                </tr>
                <tr>
                    . . .
                </tr>
            </table>
        </form>
    </div>
  2. Click the TimeSheetEvaluation.ts tab and change the document as follows:
    function evaluateDailySalary(day: string, salary: number, time: number) {
        let pay = function (x, y) { return x * y; }
    
        document.getElementById(day).innerHTML = pay(salary, time).toFixed(2);
    }
    
    function calculate() {
        const hSalary: number = Number((document.querySelector("#hourlySalary") as HTMLInputElement).value || 0);
        const mon: number = Number((document.querySelector("#monday") as HTMLInputElement).value || 0);
        const tue: number = Number((document.querySelector("#tuesday") as HTMLInputElement).value || 0);
        const wed: number = Number((document.querySelector("#wednesday") as HTMLInputElement).value || 0);
        const thu: number = Number((document.querySelector("#thursday") as HTMLInputElement).value || 0);
        const fri: number = Number((document.querySelector("#friday") as HTMLInputElement).value || 0);
    
        const married: boolean = (document.querySelector("#isMarried") as HTMLInputElement).checked;
    
        let multiplication: (x: number, y: number) => number = function (x: number, y: number) { return x * y; }
        let addition: (a: number, b: number, c: number, d: number, e: number) => number =
            function (a: number, b: number, c: number, d: number, e: number) { return a + b + c + d + e; }
    
        const weeklySalary: number = multiplication(addition(mon, tue, wed, thu, fri), hSalary);
    
        evaluateDailySalary("salaryMonday", hSalary, mon);
        evaluateDailySalary("salaryTuesday", hSalary, tue);
        evaluateDailySalary("salaryWednesday", hSalary, wed);
        evaluateDailySalary("salaryThursday", hSalary, thu);
        evaluateDailySalary("salaryFriday", hSalary, fri);
    
        let netPay: number;
    
        let witholdingTax = 88.72;
    
        if (married === true) {
            witholdingTax = 64.11;
        }
    
        netPay = weeklySalary - witholdingTax;
    
        document.getElementById("weeklySalary").innerHTML = netPay.toFixed(2);
    }
  3. Click the PayrollPreparation.cshtml tab to acticvate the view
  4. Press Ctrl + F5 to execute the application:

    Checking a Check Box

  5. In the text boxes, type the following values:
    Hourly Salary: 21.37
    Monday:        8.00
    Tuesday:       7.00
    Wednesday:     9.50
    Thursday:      7.50
    Friday:        9.00
  6. Click the Calculate button:

    Checking a Check Box

  7. Click the Employee Is Married check box
  8. Click the Calculate button

    Checking a Check Box

  9. Close the browser and return to your programming environment

Radio Buttons

A radio button is a small round control. Although you can have one radio button, they are usually created in a group of at least two of them and they are referred to as mutually exclusive. This means that only one of the radio buttons in a group can be checked at a time.

To get a radio button, create an INPUT tag and set its TYPE attribute to RADIO. Normally, you should create the control in a tag that can hold other tags and then add other radio buttons to the same group. All of the radio buttons of the same group should (must) have the same NAME value.

When creating radio buttons, if you want one of them to automatically be selected, add a CHECKED attribute to the tag.

A Text Box

As you may be aware, the text box is the most common control of an application. It primarily holds or receives some text. When a user has finished using your form, he or she can click a button. To make sure that the user provides a value for a text box, the INPUT tag provides an attribute named REQUIRED. In HTML, this attribute doesn't use a value. When this attribute is set, if the user doesn't provide a value for its text box, the browser would display an error.

Combo Boxes

A combo box is a control that presents a list of values when the user clicks an arrow button.

To let you create a combo box, HTML provides a tag named SELECT. To let you create the items of a combo box, HTML provides a tag named OPTION. This tag is created between the SELECT starting and closing tag.

Practical LearningPractical Learning: Creating a Combo Box

  1. Click the PayrollEvaluation.cshtml tab and change the document as follows:
    @{
        ViewBag.Title = "Payroll Evaluation";
    }
    
    <h2 class="common-font text-center bold">Payroll Evaluation</h2>
    
    <hr />
    
    <div class="delimiter common-font">
        <form name="PayrollEvaluation" method="post">
            <table class="table table-striped">
                <tr>
                    <td class="large-text bold">Hourly Salary:</td>
                    <td><input class="form-control small" id="hourlySalary" /></td>
                    <td>&nbsp;</td>
                    <td class="bold">Marital Status:</td>
                    <td>
                        <select class="form-control small" id="maritalStatus">
                            <option value="Single">Single</option>
                            <option value="Married">Married</option>
                        </select>
                    </td>
                    <td>&nbsp;</td>
                </tr>
                <tr>
                    <td class="large-text bold">Days</td>
                    <td class="bold text-center">Monday</td>
                    <td class="bold text-center">Tuesday</td>
                    <td class="bold text-center">Wednesday</td>
                    <td class="bold text-center">Thursday</td>
                    <td class="bold text-center">Friday</td>
                </tr>
                <tr>
                    <td class="bold">Time Worked:</td>
                    <td><input type="number" class="form-control small" id="monday" /></td>
                    <td><input type="number" class="form-control small" id="tuesday" /></td>
                    <td><input type="number" class="form-control small" id="wednesday" /></td>
                    <td><input type="number" class="form-control small" id="thursday" /></td>
                    <td><input type="number" class="form-control small" id="friday" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td class="text-center" colspan="5">
                        <input type="button" id="btnCalculate" class="btn btn-primary"
                               style="width: 500px" value="Calculate" onclick="calculate()" />
                    </td>
                </tr>
                <tr>
                    <td class="bold">Daily Salary:</td>
                    <td><span id="salaryMonday"></span></td>
                    <td><span id="salaryTuesday"></span></td>
                    <td><span id="salaryWednesday"></span></td>
                    <td><span id="salaryThursday"></span></td>
                    <td><span id="salaryFriday"></span></td>
                </tr>
                <tr>
                    <td colspan="4">&nbsp;</td>
                    <td class="bold">Weekly Salary:</td>
                    <td><span id="weeklySalary"></span></td>
                </tr>
            </table>
        </form>
    </div>
    
    <script src="~/Scripts/TimeSheetEvaluation.js"></script>
  2. Click the TimeSheetEvaluation.ts tab and change the document as follows:
    function evaluateDailySalary(day: string, salary: number, time: number) {
        let pay = function (x, y) { return x * y; }
    
        document.getElementById(day).innerHTML = pay(salary, time).toFixed(2);
    }
    
    function calculate() {
        const hSalary: number = Number((document.querySelector("#hourlySalary") as HTMLInputElement).value || 0);
        const mon: number = Number((document.querySelector("#monday") as HTMLInputElement).value || 0);
        const tue: number = Number((document.querySelector("#tuesday") as HTMLInputElement).value || 0);
        const wed: number = Number((document.querySelector("#wednesday") as HTMLInputElement).value || 0);
        const thu: number = Number((document.querySelector("#thursday") as HTMLInputElement).value || 0);
        const fri: number = Number((document.querySelector("#friday") as HTMLInputElement).value || 0);
    
        const mStatus: string = (document.querySelector("#maritalStatus") as HTMLInputElement).value;
    
        let multiplication: (x: number, y: number) => number = function (x: number, y: number) { return x * y; }
        let addition: (a: number, b: number, c: number, d: number, e: number) => number =
            function (a: number, b: number, c: number, d: number, e: number) { return a + b + c + d + e; }
    
        const weeklySalary: number = multiplication(addition(mon, tue, wed, thu, fri), hSalary);
    
        evaluateDailySalary("salaryMonday", hSalary, mon);
        evaluateDailySalary("salaryTuesday", hSalary, tue);
        evaluateDailySalary("salaryWednesday", hSalary, wed);
        evaluateDailySalary("salaryThursday", hSalary, thu);
        evaluateDailySalary("salaryFriday", hSalary, fri);
    
        let netPay: number;
    
        let witholdingTax = 88.72;
    
        if (mStatus === "Single") {
            witholdingTax = 64.11;
        }
    
        netPay = weeklySalary - witholdingTax;
    
        document.getElementById("weeklySalary").innerHTML = netPay.toFixed(2);
    }
  3. Click the PayrollEvaluation.cshtml tab to activate it
  4. Press Ctrl + F5 to execute the application:

    Ceil Inn - Employees Records

  5. In the text boxes, type the following values:
    Hourly Salary: 16.83
    Monday:        5.00
    Tuesday:       6.00
    Wednesday:     4.50
    Thursday:      6.50
    Friday:        7.00
  6. Click the Calculate button:

    Checking a Check Box

  7. In the combo box, select Married
  8. Click the Calculate button

    Creating and Using a Combo Box

  9. Close the browser and return to your programming environment
  10. Close your programming environment

Previous Copyright © 2018-2019, FunctionX Next