1.1 Buttons and Inputs

In this exercise, you implement some simple features using the app template. The goal is to become familiar with HTML and JavaScript as well as with the app template.

Make a copy of the application template for each of the tasks below, and write the necessary code with JavaScript and HTML to solve the tasks below.

a) Hello World!

Add the necessary code to write the text "Hello World!" to the console!

Use the writeLog() function from the web helper library!

Solution:

b) Odd or even

Allow the user to enter a number. Write a program that determines whether that number is odd or even when the user presses a button. Print the result to the console!

Use the getInput() function from the web helper library!

Use an if-then-else statement to check whether the number is odd or even!

Solution:

c) Calculate the sum

Allow the user to enter two numbers. Write a program that adds both values together when the user presses a button. Print the result to the console!

Use parseFloat() to convert a input string into a number!

Solution:

d) Area and circumference

Allow the user to enter a number and interpret the number as the radius of a circle. Write a program that calculates the area and circumference of that circle and prints it to the console!

Create separate functions to calculate the area and circumference!

The function toFixed(2) will truncate a number at 2 decimal points.

Solution:

e) Repeating things

Re-use your program from d) to automatically calculate the area and circumference of circles with a radius of 1, 2, 3, and up to 100. Print all results to the console.

Use a loop and choose the appropriate type for this scenario!

Solution:

f) Validate input

Make sure that your program from d) can handle malicious input, such as negative values for a radius. Furthermore, clean up the input field after every press of the button.

Use a control structure to decide whether an input is valid!

You can get a reference to an input field via its unique id with document.getElementById(). The field value contains the current value of an input field, which you can set to an empty string.

Solution:

g) Math and libraries

Add two input fields. When the user presses a button, take the value from the first input field to the power of the number in the second input field and print the result to the console.

Check out the functionMath.pow()to perform the calculation. The Math library contains numerous useful functions.

Solution:

h) Change the header

This is a little useless, but shows an important point: when someone presses the button, change the heading to the text that was entered in the input field.

To get the heading in JavaScript, add an id to it and use document.getElementById()

Solution:

Last updated

Was this helpful?