Introduction to Built-In Functions and Objects |
The Window of a Web Page
Introduction to the DOM
The Document Object Model, or DOM, is a library that contains the definitions of all of the objects used to create and populate a webpage. The DOM is filled with objects used to create or populate a webpage. You can directly use those objects in your code.
Practical Learning: Creating and Using an Anonymous Function
- Start Microsoft Visual Studio
- On the main menu, click File -> New -> Project...
- In the middle frame of the New Project dialog box, make sure ASP.NET Web Application (.NET Framework) is selected.
Change the Name to PayrollPreparation4 - Click OK
- In the ASP.NET Web Application dialog box, make sure the MVC icon is selected.
Click OK - In the Solution Explorer, right-click Content -> Add -> New Item...
- In the left list of the Add New Item dialog box, under Visual C#, expand Web, and click Markup
- In the middle list, click Style Sheet
- Change the file Name to PayrollPreparation
- Click Add
- 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; }
- In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
- Change the document as follows:
using System.Web.Optimization; namespace PayrollPreparation4 { 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")); } } }
- In the Solution Explorer, expand Controllers, and click HomeController.cs
- In the class, create a method named PayrollEvaluation as follows:
using System.Web.Mvc; namespace PayrollPreparation1.Controllers { public class HomeController : Controller { . . . public ActionResult PayrollEvaluation() => View(); } }
- In the class, right-click PayrollEvaluation() -> Add View...
- Make sure the View Name text box is displaying PayrollEvaluation.
Click Add - In the Solution Explorer, right-click Scripts -> Add -> New Item...
- In the left list of the New Item dialog box, under Visual C# and under Web, click Scripts
- In the middle list, click TypeScript File
- Change the file Name to TimeSheetEvaluation
- Click Add
Introduction to the Browser
A webpage is an object that displays in an application called a browser. A webpage is surrounded by borders. It has a title bar and may contain tabs. It presents a wide area that presents the content aimed at serving the visitor of a website.
An HTML Element
As you may know already, a webpage is a text-based document that contains text-based tags to instruct the browser about what to do with the document. The tags are created using standardized formats starting with a name. Examples of names of HTML tags are HTML, TITLE, BODY, DIV, HEADER, SECTION, P, A, UL, LI, TABLE, TR, TD, PRE, etc.
To support the tags of a webpage, the DOM provides an ancestral object named Element. This object contains the common characteristics (properties) that describe all or most tags. The class also contains methods for the actions that a tag can take.
Practical Learning: Introducing HTML Elements
- Click the PayrollEvaluation.cshtml tab to access it
- 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"> <table> <tr> <td class="large-text bold">Hourly Salary:</td> <td><span class="form-control small" id="hourlySalary"></span></td> </tr> </table> <table class="table table-striped"> <tr> <td class="large-text bold"> </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><span class="form-control small"></span></td> <td><span class="form-control small"></span></td> <td><span class="form-control small"></span></td> <td><span class="form-control small"></span></td> <td><span class="form-control small"></span></td> </tr> <tr> <td class="bold">Daily Salary:</td> <td><span></span></td> <td><span></span></td> <td><span></span></td> <td><span></span></td> <td><span></span></td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> <td class="bold">Weekly Salary:</td> <td><span></span></td> </tr> </table> </div> <script src="~/Scripts/TimeSheetEvaluation.js"></script>
The Document of a Web Page
As you are probably aware already, a webpage starts as a normal text-based document in which you add the necessary HTML tags to create the desired content. To support the document as an object, the DOM provides an object named document.
The Root of a Web Page
The most fundamental tag of a webpage is named HTML. It includes, and serves as the parent of, everything or every other tag on a webpage. Therefore, it is called the root element.
To give you access to the root element of a webpage, the document object is equipped with a property named documentElement:
let element = document.documentElement;
The document.documentElement property holds a collection of all the elements or HTML tags of a webpage.
Writing to a Document
To allow you to programmatically write something to a webpage, the document object is equipped with a method named write. Its syntax is:
document.write(markup);
This method takes a string as argument. You can pass a regular string to the method. One of the strengths of the document.write() method is that its argument can include HTML markup. It this case, the method would produce the word, paragraph, or section as it is meant to display as an HTML formatted item.
A Window Object
To support the window in a browser, the DOM provides an object named window.
A Message Box
A message box is a rectangular box you can use to a relatively short window with text on top of the browser. To support it, the window object is equipped with a method named alert. Its syntax is:
alert(message);
This method takes a string as an optional argument. Otherwise, pass a string as argument for the message you want to display. Here is an example:
TypeScript File: Administration.js
alert("To contact us, please click the Contact link");
View: About.cshtml
@{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<p>Use this area to provide additional information.</p>
<script src="~/Scripts/Administration.js"></script>
This would produce:
The Location of a Document
Introduction
The Internet is large network of connected computers. The most important aspect of the Internet is that the connected computers hold billions of documents that are of interest to Web visitors. The place where the document is stored is called a location. To support the concept of document location, the DOM provides an object named location.
To make it easy for you to deal with the location of a document, both the window and the document objects are equipped with a property named location. This means that when using either the window object or the document object, you can access the location object from them.
The URL of a Document
The most important piece of information about a document on the internet is its address, that is, how and where to find the document. To support this aspect, the location object is equipped with a property named href:
string = object.href; object.href = string;
This read-write property, on one hand, allows you to provide the address of a document you want to access. This is done by assigning a string as location to this property.
Introduction to Web Forms
Introduction
While the majority of webpages on the Internet are made for viewing only, if you want your visitors to interact with you, you may have to create a form. Fortunately, HTML provides most of the objects you will need. These objects are called Web controls. They are in different categories. Some controls are created using a specific HTML tag. Many other controls are created using a tag named INPUT. With that tag, to create a specific control, you would add an attribute named TYPE and assign the type of that control as a string.
Creating a Form
To let you create a form, HTML provides a tag named FORM. Use it to create a form. Here is an example:
<form></form>
Between the start and en tags, you can create the necessary content.
ASP.NET MVC supports form creation through a mechanism as follows:
@using (Html.BeginForm()) { }
Between the curly brackets, {}, create the necessary content.
Introduction to Web Controls
Introduction
To make your webpage interactive, you can equip it with various types of Web controls. HTML supports many of them. The primary way to create a control is with a tag named INPUT. It is equipped with an attribute named TYPE. To specify the type of control you want, you will assign the appropriate name to that attribute.
To support Web controls, ASP.NET MVC provides various techniques. In ASP.NET MVC, most Web controls are created by calling a method on @Html. This would be done as follows:
@using (Html.BeginForm()) {
<p><b>Full Name:</b> @Html.method-name()</p>
}
The Name of a Control
When creating a control, you can give it a name. To support names, almost all HTML Web controls are equipped with an attribute named NAME. To name a control, assign the desired string to that attribute. Here are examples
<form name="ToysCatalog"> <p><b>Full Name:</b> <input name="fullName" /></p> </form>
To support the names of Web controls, pass that name as the first argument to the method used to create the control. Here is an example:
@using (Html.BeginForm()) {
<p><b>Full Name:</b> @Html.method("FullName")</p>
}
The Value of a Control
The value of a control depends on the type of control. For some controls, the value is the text, number, date, etc, that the control is displaying. It can also be the text, number, date, etc, that must be given to the control. To let you specify the value of a text box, the INPUT tag is equipped with an attribute named VALUE. To use it, assign the desired string to it. Here is an example:
<input type="text" value="3.14156" />
In ASP.NET MVC, to specify the value of a control, in most cases, you pass a second argument to the method that control. That argument must hold the value you want to use. Here is an example:
@{
ViewBag.Title = "Review";
string fullName = "Paul Bertrand Yamaguchi";
}
<h2>Review</h2>
@using (Html.BeginForm())
{
<p><b>Full Name:</b> @Html.method("FullName", @fullName)</p>
}
Identifying a Control
To help you identify an object in a Web page, each HTML tag is equipped with an attribute named ID. To identify an object, provide a value to it. That value must be unique among the other objects on the same webpage.
In ASP.NET MVC, to specify the identity of a control, add an htmlAttributes argument to the method that creates a control. In the body of that argument, create an ID attribute and assign the desired value to it as a string. Here is an example:
@using (Html.BeginForm()) {
<p><b>Full Name:</b> @Html.method("FullName", null,
htmlAttributes: new { id = "fullName" })</p>
}
Practical Learning: Identifying the Controls
- 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"> <table> <tr> <td class="large-text bold">Hourly Salary:</td> <td><span class="form-control small" id="hourlySalary"></span></td> </tr> </table> <table class="table table-striped"> <tr> <td class="large-text bold"> </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><span class="form-control small" id="monday"></span></td> <td><span class="form-control small" id="tuesday"></span></td> <td><span class="form-control small" id="wednesday"></span></td> <td><span class="form-control small" id="thursday"></span></td> <td><span class="form-control small" id="friday"></span></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> </td> <td> </td> <td> </td> <td> </td> <td class="bold">Weekly Salary:</td> <td><span id="weeklySalary"></span></td> </tr> </table> </div>
Locating an Element by its Identifier
To let you access a tag based on its ID attribute, the document object is equipped with a method named getElementById. Its syntax is:
var element = document.getElementById(id);
This method produces an Element object.
Practical Learning: Identifying Controls
- Click the 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 = 17.13; const mon: number = 6.00; const tue: number = 5.00; const wed: number = 7.00; const thu: number = 6.50; const fri: number = 7.00; 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); document.getElementById("hourlySalary").innerHTML = hSalary.toFixed(2); document.getElementById("monday").innerHTML = mon.toFixed(2); document.getElementById("tuesday").innerHTML = tue.toFixed(2); document.getElementById("wednesday").innerHTML = wed.toFixed(2); document.getElementById("thursday").innerHTML = thu.toFixed(2); document.getElementById("friday").innerHTML = fri.toFixed(2); evaluateDailySalary("salaryMonday", hSalary, mon); evaluateDailySalary("salaryTuesday", hSalary, tue); evaluateDailySalary("salaryWednesday", hSalary, wed); evaluateDailySalary("salaryThursday", hSalary, thu); evaluateDailySalary("salaryFriday", hSalary, fri); document.getElementById("weeklySalary").innerHTML = weeklySalary.toFixed(2); } calculate();
- Click the PayrollEvaluation.cshtml to activate it
- To execute, on the main menu, click Debug -> Start Without Debugging:
- Close the browser and return to your programming environment
Querying by Selecting the Identifier
The DOM provides a general way to locate an element in a webpage. This is done by using a method named querySelector of the document object. The syntax of the document.querySelector() method is:
element = document.querySelector(selectors);
This method takes a string as argument. The content of that string depends on the category of item you are trying to access. If you select an element based on its ID, pass the value of that attribute to the document.querySelector() as a string.
Practical Learning: Selecting an Element by its Identifier
- Click the PayrollEvaluation.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.querySelector(day).innerHTML = pay(salary, time).toFixed(2); } function calculate() { const hSalary: number = 22.66; const mon: number = 7.50; const tue: number = 8.00; const wed: number = 8.50; const thu: number = 9.50; const fri: number = 6.00; 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); document.querySelector("#hourlySalary").innerHTML = hSalary.toFixed(2); document.querySelector("#monday").innerHTML = mon.toFixed(2); document.querySelector("#tuesday").innerHTML = tue.toFixed(2); document.querySelector("#wednesday").innerHTML = wed.toFixed(2); document.querySelector("#thursday").innerHTML = thu.toFixed(2); document.querySelector("#friday").innerHTML = fri.toFixed(2); evaluateDailySalary("#salaryMonday", hSalary, mon); evaluateDailySalary("#salaryTuesday", hSalary, tue); evaluateDailySalary("#salaryWednesday", hSalary, wed); evaluateDailySalary("#salaryThursday", hSalary, thu); evaluateDailySalary("#salaryFriday", hSalary, fri); document.querySelector("#weeklySalary").innerHTML = weeklySalary.toFixed(2); } calculate();
Selecting by a CSS class
One way to use the document.querySelector() method to select an element is to first add a CSS class to a tag. The class doesn't have to exist in a style section or a CSS file. This means that you can add a CSS class to a tag and give it any value. Here are examples:
@{ ViewBag.Title = "Toys Presentation"; } <h2>Toys Presentation</h2> <hr /> <p><b>Item #:</b> <span class="itemNbr"></span></p> <p><b>Product Name:</b> <span class="toyName"></span></p> <p><b>Unit Price:</b> <span class="toyPrice"></span></p> <script src="~/Scripts/ToyExamination.js"></script>
Then, to access the tag based on the CSS class, pass the value of the class to the document.querySelector() method. The value you pass must be preceded by a period. Here are examples:
let truck = this; this.price = 44.86; truck.itemNumber = 280384; this.name = "Mini Drone Quadcopter"; document.querySelector(".itemNbr").innerHTML = truck.itemNumber; document.querySelector(".toyName").innerHTML = this.name; document.querySelector(".toyPrice").innerHTML = this.price.toFixed(2);
Introduction to HTML Events
Overview
An event is something that occurs to an object on a webpage. Examples are a user moving the mouse on top of a control or typing something in a text box. The object on which the event occurs is said to fire the event.
HTML supports various types of events. Some events can be fired by any HTML tag and some events are made for some particular tags or some specific situations. Each event has a name.
One of the ways you use an event is to apply it to the desired tag in your webpage. The event is applied by adding its attribute to the tag. This would be done as follows:
<p><b>Full Name:</b> <control-creation event-name = /></p>
To specify what will happen when the object fires the event, you must assign something to the attribute. In most cases, you can create a function and assign its call to the event. This would be done as follows:
TypeScript File: EmployeeTimeSheetManagement.ts
function Finalize() { alert("Make sure you submit your time sheet, otherwise you won't get paid."); }
View: TimeSheet.cshtml
@{
ViewBag.Title = "Employee Time Sheet";
}
<h2>Employee Time Sheet</h2>
<control-creation event-name="Finalize()"
value="Finalize your Application" />
<script src="~/Scripts/EmployeeTimeSheetManagement.js"></script>
Loading the Window of a Web Page
When a browser is asked to display a webpage, the browser has to check and/or validate a few things. At one time, if everything is alright, the webpage displays, but just before displaying the webpage, the browser fires an event named load. To use this event, add an attribute named onload to the HTML tag to which you want to apply it.
If you want to do something on the webpage as soon as it displays, apply the onload event to the window object. Usually, you add this event as an attribute to the <BODY> tag of the webpage.
The Click Event
When a user clicks an object, such as a piece of text, a section of a web, or a button, the item fires an event named onclick. To use it, add it as attribute to the desired HTML tag and assign the desired action to it. Here is an example:
TypeScript File: RegistrationValidation.ts
function ValidateRegistration() { alert("The vehicle registration is not complete. Please check the owner's date of birth."); }
View: VehicleRegistration.cshtml
@{
ViewBag.Title = "Vehicle Registration";
}
<h2>Vehicle Registration</h2>
<p id="checkRegistration"
class="btn btn-default"
onclick="ValidateRegistration()">Check Registration</p>
<script src="~/Scripts/VehiclesDepartment.js"></script>
Losing Focus
An object is said to lose focus when the user clicks another object (an object other than the one that previously had focus). When that happens, the element, usually a Web control, fires an event named onblur. Any Web control control can fire this event but use it only for the control(s) that need it on your form.
A Review of Web Controls
A Button
A button is a rectangular control that a user can click to initiate an action. To get a button, create an INPUT tag and set its TYPE as BUTTON. As mentioned for the creation of controls, you can also specity the name, the identification, the value, etc, of the control. Here is an example:
<input type="button" id="finalize" value="Finalize your Application" />
Most of the time, you create a button to ask users to click it. When that happens, you must provide an action. This can be done by assigning a function to the onclick event of the button. Here is an example:
@{
ViewBag.Title = "Vehicle Registration";
}
<h2>Vehicle Registration</h2>
<input type="button" id="checkRegistration"
class="btn btn-primary" value="Check Registration"
onclick="ValidateRegistration()" />
<script src="~/Scripts/VehiclesDepartment.js"></script>
Submitting a Form
HTML allows you to create a form that would automatically process something when the form's main button is clicked. To make this happen, create an INPUT tag and set its TYPE as SUBMIT.
Resetting a Form
Resetting a form consists of setting its controls to their default values when a certain button is clicked. To make this happen, create an INPUT tag and set its TYPE as RESET.
A Text Box
A text box is a control used to get or present text. To let you get it, simply create an INPUT tag. Here is an example:
@{
ViewBag.Title = "Toys Catalog";
}
<h2>Toys Catalog</h2>
<form name="ToysCatalog">
<p><b>Full Name:</b> <input /></p>
</form>
Otherwise, to explicitly get a text box, create an INPUT tag and add a TYPE attribute to it. Set the value of this attribute to TEXT.
To create a text box in ASP.NET MVC, call a method named TextBox on the @Html object. Here is an example:
@using (Html.BeginForm()) {
<p><b>Full Name:</b> @Html.TextBox()</p>
}
As one way to specify the value of a text box in ASP.NET MVC, pass a second argument to the @Html.TextBox() method. Here is an example:
@{
ViewBag.Title = "Review";
string fullName = "Paul Bertrand Yamaguchi";
}
<h2>Review</h2>
@using (Html.BeginForm())
{
<p><b>Full Name:</b> @Html.TextBox("FullName", @fullName)</p>
}
A Numeric Text Box
To assist you in creating a text box specifically made for numbers, the INPUT tag provide the NUMBER value for the TYPE attribute.
Practical Learning: Creating a Form
- 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 colspan="4"> </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> </td> <td class="text-center" colspan="5"> <input type="button" id="btnCalculate" class="btn btn-primary" style="width: 500px" value="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"> </td> <td class="bold">Weekly Salary:</td> <td><span id="weeklySalary"></span></td> </tr> </table> </form> </div> <script src="~/Scripts/TimeSheetEvaluation.js"></script>
Other INPUT Web Controls
In HTML, most controls are created from the INPUT tag and its TYPE attribute. To get one of those controls, start with the INPUT tag and assing the appropriate name to the TYPE attribute. The available names are BUTTON, SUBMIT, RESET, FILE, RANGE, HIDDEN, DATE, TIME, DATETIME, URL, PASSWORD, EMAIL, etc.
Common Properties for INPUT Elements
In our introduction, we saw that the DOM provides the Element object to lay a foundation for most HTML elements functionalities. To provide some particular characteristics of HTML elements created with the INPUT tag, the DOM provides an object named HTMLInputElement (it is actually an interface). This object allows you to control such aspects as the name, the type, the value, etc. It also makes it possible to deal with events of an element.
Form Interaction with TypeScript
In JavaScript, in a webpage that contains a form, you can write the code that deals with Web controls for interactivity. Here is an example:
@{ ViewBag.Title = "Employment Application"; } <h2>Employment Application</h2> <form name="EmploymentApplication"> <table> <tr> <td>First Name:</td> <td><input type="text" id="firstName" value="Marianne" /></td> </tr> <tr> <td>Last Name:</td> <td><input type="text" id="lastName" value="Curryan" /></td> </tr> <tr> <td>Full Name:</td> <td><input id="fullName" /></td> </tr> </table> </form> <script> var fName = document.EmploymentApplication.firstName.value; var lName = document.EmploymentApplication.lastName.value; document.querySelector("#fullName").value = fName + ' ' + lName; </script>
The above code used the name of a form to access the controls on that form. As an alternative, you can use the document.querySelector() method to access a control. Here are examples:
@{ ViewBag.Title = "Employment Application"; } <h2>Employment Application</h2> <form name="EmploymentApplication"> <table> <tr> <td>First Name:</td> <td><input type="text" id="firstName" value="Marianne" /></td> </tr> <tr> <td>Last Name:</td> <td><input type="text" id="lastName" value="Curryan" /></td> </tr> <tr> <td>Full Name:</td> <td><input id="fullName" /></td> </tr> </table> </form> <script> var fName = document.querySelector("#firstName").value; var lName = document.querySelector("#lastName").value; document.querySelector("#fullName").value = fName + ' ' + lName; </script>
You may be tempted to write the same code in TypeScript. Here is an example:
View: EmploymentApplication.cshtml
@{ ViewBag.Title = "Employment Application"; } <h2>Employment Application</h2> <form name="EmploymentApplication"> <table> <tr> <td>First Name:</td> <td><input type="text" id="firstName" value="Marianne" /></td> </tr> <tr> <td>Last Name:</td> <td><input type="text" id="lastName" value="Curryan" /></td> </tr> <tr> <td>Full Name:</td> <td><input id="fullName" /></td> </tr> </table> </form> <script src="~/Scripts/ProcessHiring.js"></script>
TypeScript File: ProcessHiring.ts
var fName = document.querySelector("#firstName").value; var lName = document.querySelector("#lastName").value; document.querySelector("#fullName").value = fName + ' ' + lName;
When this code is execute, although it may display the webpage, it is actually in error. This is because the TypeScript code cannot directly values from the form of a webpage. Instead, you must cast them to the appropriate value. To do that, you can precede the document.querySelector() call with the HTMLInputElement object. This object must be provided as a starting tag. This would be done as follows:
View: EmploymentApplication.cshtml
@{ ViewBag.Title = "Employment Application"; } <h2>Employment Application</h2> <form name="EmploymentApplication"> <table> <tr> <td>First Name:</td> <td><input type="text" id="firstName" value="Marianne" /></td> </tr> <tr> <td>Last Name:</td> <td><input type="text" id="lastName" value="Curryan" /></td> </tr> <tr> <td>Full Name:</td> <td><input id="fullName" /></td> </tr> </table> </form> <script src="~/Scripts/ProcessHiring.js"></script>
TypeScript File: ProcessHiring.ts
var fName = (<HTMLInputElement>document.querySelector("#firstName")).value; var lName = (<HTMLInputElement>document.querySelector("#lastName")).value; (<HTMLInputElement>document.querySelector("#completeName")).innerHTML = fName + ' ' + lName;
This time, the code will work just fine.
Value Conversion
Introduction
If you create a form in which a user must type a value, by default, the value the user types is a string, primarily a piece of text. If you want to consider that a value from a webpage must be involved in a numerical expression, you must first convert it. To assist you in performing conversions of values from one type to another, JavaScript provides many ready-made functions and objects you can use directly in your code.
Converting a Value to an Integer
To assist you in converting a non-numeric value to a string, JavaScript provides a function named parseInt. The syntax of this function is:
int parseInt(string, radix);
This function takes one required argument and one optional argument. The requirement argument is the value that must be converted:
- If the value contains only digits, the functions produces it as an integer
- If the value starts with one or more digits on the left side followed by non-digits, as in 2P48M83 or 256GH8424, the function returns the left digits as a number
- If the value starts with a non digit (as in Z98394) or the value contains only non-digits, the function returns a constant known as NaN (which stands for Not-A-Number)
The second argument is valid only if the first one is, based on the above description. The second argument specifies the base by which the number will be converted. It is a number between 2 and 36. If you don't pass this argument, the number 10 would be used. Here is an example:
View: Administration.cshtml
@{ ViewBag.Title = "Tickets Management"; } <h2>Tickets Management</h2> <p><b>Ticket Amount:</b> <span id="amt"></span></p> <script src="~/Scripts/TicketsSystem.js"></script>
TypeScript File: TicketEvaluation.ts
let strAmt: string = "125 dollars";
let ticketAmount: number = parseInt(strAmt);
If the value to convert is coming from a webpage, make sure you convert it after it has been cast to <HTMLInputElement>.
Converting a Value to a String
To convert a number to a string, call a method named toString(). Here is an example:
View: Administration.cshtml
@{ ViewBag.Title = "Tickets Management"; } <h2>Tickets Management</h2> <p><b>Ticket Amount:</b> <span id="amt"></span></p> <script src="~/Scripts/TicketsSystem.js"></script>
TypeScript File: TicketEvaluation.ts
let strAmt: string = "125 dollars"; let ticketAmount: number = parseInt(strAmt); document.querySelector("#amt").innerHTML = ticketAmount.toString();
Converting a Value to a Floating-Point Number
To let you convert a value to a decimal number with a precision part, JavaScript provides a function namedparseFloat. Its syntax is:
decimal parseFloat(value);
This function takes one argument as the value to be conoverted:
- If the value contains only digits, the functions produces it as an integer
- If the value starts with one or more digits on the left side followed by a non-digit, the function returns those left digits as an integer
- If the value starts with a letter or a symbol that is not a digit, the function returns NaN
Normally, a floating-point number is made of two sections separated by the character designated by as the desimal separator. If the argument is a floating-point number, then the function will return it.
To convert the number to a string, call the toString() method on that number.
Practical Learning: Introducing Built-In Functions
- 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() { let hSalary: number = parseFloat((<HTMLInputElement>document.querySelector("#hourlySalary")).value); let mon: number = parseFloat((<HTMLInputElement>document.querySelector("#monday")).value); let tue: number = parseFloat((<HTMLInputElement>document.querySelector("#tuesday")).value); let wed: number = parseFloat((<HTMLInputElement>document.querySelector("#wednesday")).value); let thu: number = parseFloat((<HTMLInputElement>document.querySelector("#thursday")).value); let fri: number = parseFloat((<HTMLInputElement>document.querySelector("#friday")).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); document.getElementById("hourlySalary").innerHTML = hSalary.toFixed(2); document.getElementById("monday").innerHTML = mon.toFixed(2); document.getElementById("tuesday").innerHTML = tue.toFixed(2); document.getElementById("wednesday").innerHTML = wed.toFixed(2); document.getElementById("thursday").innerHTML = thu.toFixed(2); document.getElementById("friday").innerHTML = fri.toFixed(2); evaluateDailySalary("salaryMonday", hSalary, mon); evaluateDailySalary("salaryTuesday", hSalary, tue); evaluateDailySalary("salaryWednesday", hSalary, wed); evaluateDailySalary("salaryThursday", hSalary, thu); evaluateDailySalary("salaryFriday", hSalary, fri); document.getElementById("weeklySalary").innerHTML = weeklySalary.toFixed(2); }
- 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 colspan="4"> </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> </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"> </td> <td class="bold">Weekly Salary:</td> <td><span id="weeklySalary"></span></td> </tr> </table> </form> </div> <script src="~/Scripts/TimeSheetEvaluation.js"></script>
- To execute the project, on the main menu, click Debug -> Start Without Debugging:
- In the text boxes, enter the following values:
Hourly Salary: 17.63 Monday: 8 Tuesday: 10.00 Wednesday: 7.50 Thursday: 9.00 Friday: 10.50
- Click the Evaluate button:
- Close the browser and return to your programming environment
Numbers
Introduction
JavaScript supports numbers in many ways. The primary way is through an object named Number (N in uppercase and the other letters in lowercase). You can use this class to initiate a number. To do this, declare a variable and initialize it using the new operator. Pass the desired expression or number to the constructor of this object. Here is an example:
let first = new Number(28.85);
If you want, you can indicate the data type of the variable as Number. Here are examples:
function create(start, rent, plays) {
let bill = this;
bill.basicFee = start;
bill.dvr = rent;
bill.sports = plays;
bill.fccFee = 1.05;
bill.total = function () {
return this.basicFee + this.dvr + this.sports + this.fccFee;
};
bill.calcTaxes = function (rate) {
var taxes = this.total() * rate / 100;
return taxes;
}
return bill;
};
let first: Number = new Number(28.85);
let recorder: Number = new Number(8.95);
let play: Number = new Number(12.95);
var pay = create(first, recorder, play);
Converting a Number
Converting, or parsing, a number consists of analyzing it to make it possible to use it appropriately. The Number (again, N in uppercase and the other letters in lowercase) object provides its own mechanism to perform a conversion. To convert a number, use its constructor as a method. As mentioned already, it takes a value or expression as argument. The formula to use it is:
Number(expression || 0);
Pass an expression or a value to Number followed by || 0. If the expression or value is successfully converted to a number, this method returns that number. If the conversion fails, the || 0 expression indicates that the method should returns 0. You can then assign the method call to a variable:
variable = Number(expression || 0);
Formatting a Number
One of the most important features of the Number object is its ability to format a number so it can be displayed the way you want to the user. The Number object does this through various methods.
To let you format a number to an exponential value, the Number object provides a method named toExponential. To let you format a number to a precision of your choice, the object provides a method named toPrecision. To allow you to format a number to a fixed precision, the Number object provides a method named toFixed. Its syntax is:
toFixed([digits])
This method takes one argument that is optional. The value of this argument is a number between 0 and 20. The value represents the number of digits that would appear after the decimal point. If you don't pass this argument, the method would use 0. Otherwise, make sure you pass a value of your choice.
Practical Learning: Formatting Numbers
- 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() { let hSalary: number = Number((<HTMLInputElement>document.querySelector("#hourlySalary")).value || 0); let mon: number = Number((<HTMLInputElement>document.querySelector("#monday")).value || 0); let tue: number = Number((<HTMLInputElement>document.querySelector("#tuesday")).value || 0); let wed: number = Number((<HTMLInputElement>document.querySelector("#wednesday")).value || 0); let thu: number = Number((<HTMLInputElement>document.querySelector("#thursday")).value || 0); let fri: number = Number((<HTMLInputElement>document.querySelector("#friday")).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); document.getElementById("hourlySalary").innerHTML = hSalary.toFixed(2); document.getElementById("monday").innerHTML = mon.toFixed(2); document.getElementById("tuesday").innerHTML = tue.toFixed(2); document.getElementById("wednesday").innerHTML = wed.toFixed(2); document.getElementById("thursday").innerHTML = thu.toFixed(2); document.getElementById("friday").innerHTML = fri.toFixed(2); evaluateDailySalary("salaryMonday", hSalary, mon); evaluateDailySalary("salaryTuesday", hSalary, tue); evaluateDailySalary("salaryWednesday", hSalary, wed); evaluateDailySalary("salaryThursday", hSalary, thu); evaluateDailySalary("salaryFriday", hSalary, fri); document.getElementById("weeklySalary").innerHTML = weeklySalary.toFixed(2); }
- Click the PayrollEvalluation.cshtml tab to activate the document
- To execute, on the main menu, click Debug -> Start Without Debugging
- In the text boxes, enter the following values:
Hourly Salary: 42.59 Monday: 6.00 Tuesday: 7.50 Wednesday: 5.00 Thursday: 10.00 Friday: 6.50
- Click the Calculate button
- Close the browser and return to your programming environment
- Close your programming environment
|
||
Previous | Copyright © 2018-2019, FunctionX | Next |
|