In this lab, we will learn to write simple JavaScript programs.
We will use Aptana to write JavaScript code inside of our web pages. Remember that JavaScript code is part of a web page, so you must save your web page with a .html extension. The JavaScript code is inside a script tag.
TASK: Open Aptana (Start->All Programs->Aptana) and create a new project. Choose your F:\COSC122\lab6 folder as your workspace. Cancel the Git Support Configuration if you are asked.
TASK: To create a new project, select File->New->Project...
TASK: In the next window, under the General tab pick Project and click the Next button.
TASK: In the next window, enter Lab 6 for a name then click Finish.
TASK: Select your Project Explorer. To create a new HTML file, right-click on your project name (Lab 6) and select New From Template->HTML->HTML - 4.01 Strict Template. Call the file HelloWorld_JS.html. Make sure the new file is created inside the project Lab 6!
Insert the javascript code below between the body tags of your HTML file.
TASK: Preview your code by clicking on the Show Preview Editor icon.
As practice, let's consider how we could create a program that does these things:
Think about how you would solve the problem for a minute. In a new file called addTwoNumbers.html, try to write the code yourself. Did your code solve the problem? Most likely, you were close, but when you used "+" JavaScript performed string concatenation instead of number addition. It did that because the window.prompt method returns strings even when the strings actually look like numbers. What you need to know is a method called parseInt(str) that will convert a string (str) into a number. See the answer below:
var number1 = window.prompt("Enter a number:"); var number2 = window.prompt("Enter a number:"); var result = parseInt(number1)+parseInt(number2); window.alert(number1+"+"+number2+"="+result);
You can also download the answer. A screenshot is below.
You will create two separate JavaScript programs to submit in the assignment. The first should be saved in a file called lab6_1.html and the second in a file called lab6_2.html.
Create a program that:
Create an improved program compared to task 1 that:
For this lab assignment, submit using Blackboard Connect your two answer files lab6_1.html and lab6_2.html.