Question

In: Computer Science

7.14 LAB: Temperature conversion In this lab, you will implement a temperature converter. Five UI elements...

7.14 LAB: Temperature conversion

In this lab, you will implement a temperature converter. Five UI elements are declared for you in the template:

Element's ID Element description
cInput Text input field for Celsius temperature
fInput Text input field for Fahrenheit temperature
convertButton Button that, when clicked, converts from one temperature to the other
errorMessage Div for displaying an error message when temperature cannot be converted
weatherImage Image corresponding to the temperature

Implement the conversion functions (2 points)

Implement the convertCtoF() and convertFtoC() functions to convert between Celsius and Fahrenheit. convertCtoF() takes a single numerical argument for a temperature in Celsius and returns the temperature in Fahrenheit using the following conversion formula:

°F = °C * 9/5 + 32

Similarly, convertFtoC() takes a single numerical argument for a temperature in Fahrenheit and returns the temperature in Celsius using the following conversion formula:

°C = (°F - 32) * 5/9

Register conversion button's click event in domLoaded() (2 points)

When the DOM finishes loading, the domLoaded() function is called. Implement domLoaded() to register a click event handler for the Convert button (id="convertButton"). Use addEventListener(), not onclick.

When the Convert button is pressed, the text box that contains a number should be converted into the opposing temperature. So if a number is in the Celsius text box (id="cInput"), the temperature should be converted into Fahrenheit and displayed in the Fahrenheit text box (id="fInput") and vice versa. Use parseFloat() to convert from a string to a number and do not round the result.

Ensure that only one text field contains a value (2 points)

Ensure that only one text field contains a value at any moment in time unless the Convert button has been pressed. Ex: When the Celsius field has a number and the user enters a Fahrenheit entry, the Celsius field should be cleared as soon as the user begins to type. This will require implementing an input event handler for each of the text fields that clears the opposing text field when a change occurs. Register each input event handler in the domLoaded() function. Use addEventListener(), not oninput.

Change the image to reflect the temperature (2 points)

When the temperature is converted, change the image to reflect the temperature in Fahrenheit. Each image is in the same directory as your .html page.

Below 32 F 32 - 50 F Above 50 F
cold.gif cool.gif warm.gif

Handle bad input (2 points)

When parseFloat() returns a NaN for the temperature to be converted, set errorMessage's innerHTML to the message: "X is not a number", where X is the string from the text input. When parseFloat() returns a valid number, set errorMessage's innerHTML to an empty string. The image below shows a sample error message.

-----------------------------------------------------------------------------------------------------------------------------------------------------------

CODE GIVEN:

index.html

<!DOCTYPE html>
<html lang="en">
<title>Temperature Converter</title>
<script src="convert.js"></script>
<style>
label {
display: block;
}

#errorMessage {
color: red;
}
</style>

<body>
<p>
<label for="cInput">Celsius:</label>
<input id="cInput" type="text">
</p>
<p>
<label for="fInput">Fahrenheit:</label>
<input id="fInput" type="text">
</p>
<input id="convertButton" type="button" value="Convert">
<div id="errorMessage">
</div>
<p>
<img id="weatherImage" src="warm.gif" alt="Warm">
</p>
</body>

</html>

----------------------------------------------------------------------------------------------------------------------------------------------------

convert.js

window.addEventListener("DOMContentLoaded", domLoaded);

function domLoaded() {
// TODO: Complete the function
}

function convertCtoF(degreesCelsius) {
// TODO: Complete the function
}

function convertFtoC(degreesFahrenheit) {
// TODO: Complete the function
}
----------------------------------------------------------------------------------------------------------------------------------------------------------

OTHER FILES:

cold.gif || warm.gif || cool.gif ||

Solutions

Expert Solution

convert.js

window.addEventListener("DOMContentLoaded", domLoaded);

function domLoaded() {
        var cInput = document.getElementById("cInput"); 
        var fInput = document.getElementById("fInput");
        cInput.addEventListener("input", function(){    //on input into celcius input clears the input in fahrenheit input
                document.getElementById("fInput").value = "";
        }, false);
        fInput.addEventListener("input", function(){    //on input into fahrenheit input clears the input in celcius input
                document.getElementById("cInput").value = "";
        }, false);
        var convertButton = document.getElementById("convertButton");
        convertButton.addEventListener("click", function(){     //adding click event listener
                var cInput = document.getElementById("cInput");
                var fInput = document.getElementById("fInput");
                var errMsg = document.getElementById("errorMessage");
                var img = document.getElementById("weatherImage");
                function updateImage(degreesFahrenheit) //updates the image basaed on the parameter passed
                {
                        if(degreesFahrenheit<32)
                        {
                                img.src = "cold.gif";
                                img.alt = "Cold";
                        }
                        else if(degreesFahrenheit>=32 && degreesFahrenheit<=50)
                        {
                                img.src = "cool.gif";
                                img.alt = "Cool";
                        }
                        else
                        {
                                img.src = "warm.gif";
                                img.alt = "Warm";
                        }
                }
                var degreesCelsius = parseFloat(cInput.value);  //parsing from celcius input
                var degreesFahrenheit = parseFloat(fInput.value);       //parsing from fahrenheit input
                //one of the above two is NaN
                if(cInput.value==="")   //if celcius input is clear which means user entered fahrenheit input
                {

                        if(isNaN(degreesFahrenheit))    //if degreesFahrenheit is Not a Number (NaN) then its invalid input so printing error msg
                                errMsg.innerHTML = fInput.value+"is not a number";
                        else    //in the else case
                        {
                                cInput.value = convertFtoC(degreesFahrenheit); //converting fahrenheit to celcius and updating celsius input
                                errMsg.innerHTML = "";  //clearing the error message which if so was updated previously
                                updateImage(degreesFahrenheit); //updating the image 
                        }
                        
                }
                if(fInput.value==="")   //if fahrenheit input is clear which means user entered celcius input
                {
                        if(isNaN(degreesCelsius))       //if degreesCelsius is Not a Number then printing the error msg
                                errMsg.innerHTML = cInput.value+"is not a number";
                        else    //in the else case
                        {
                                fInput.value = convertCtoF(degreesCelsius);     //converting celcius to Fahrenheit and updating the other input
                                errMsg.innerHTML = "";  //clearing previous error msg if any
                                updateImage(convertCtoF(degreesCelsius));       //updating the image based on fahrenheit value
                        }
                }
        }, false);
}

function convertCtoF(degreesCelsius) {  //function to convert celcius to fahrenheit
        return degreesCelsius*9/5 + 32;
}

function convertFtoC(degreesFahrenheit) {       //function to convert fahrenheit to celcius
        return (degreesFahrenheit-32)*5/9;
}

convert.js Screenshots

index.html Screenshot (No changes made)

Output Screenshots

Printng error message when input is not a number

Observe the image alt message as 90F > 50F and src is warm.gif

Observe as 30F < 32F image alt is Cold and src is cold.gif

Observe that since 32F<=48F<=50F the image alt is Cool and src is cool.gif

(Regarding the output image)Since those images are with you, simple add them to the directory in which this html and js files are present and they will work just fine.

Each and everything is explained within the comment section of the content.js script.

If you like my work, don't forget to hit like. Thank you!

It has been pleasure helping you :)


Related Solutions

Temperature Converter Create a temperature conversion program that will convert the following to Fahrenheit: Celsius Kelvin...
Temperature Converter Create a temperature conversion program that will convert the following to Fahrenheit: Celsius Kelvin Newton Your program should take a character which represents the temperature to convert from and a value to be converted to using the following specification: C - Celsius K - Kelvin N - Newton In addition your program should take in the following character to exit the program: X - eXit the program The numeric input for your program should be of type double....
a java code In this lab you will implement an inorder traversal, and a search for...
a java code In this lab you will implement an inorder traversal, and a search for a 2-3-4 tree. The inorder traversal will print the contents (integers) of the tree, and the search method will return a boolean, indicating whether a given key was found in the tree. Examine the provided template. The main method is provided for you, as well as a template of the Node and 2-3-4 classes. The main method will read either "inorder" or an integer...
In this lab, you will implement and evaluate the performance (run time and # of conflicts),...
In this lab, you will implement and evaluate the performance (run time and # of conflicts), for different load factors, of three hashing schemes: • linear, • quadratic, and • double hashing. The required files for this lab are Driver.java, DoubleHash.java, KeyValuePair.java, LinearProbe.java, PrimeNumber.java, QuadraticProbe.java, and country-capitals.xls. You are required to submit a short report comparing, using plots, the performance of the hashing schemes for adding and retrieving items for different load factors (try at least 0.25, 0.5, 0.65). /**...
Explain how using dSpace to implement your buck converter will limit the possible switching frequencies you...
Explain how using dSpace to implement your buck converter will limit the possible switching frequencies you can use
In this lab, you will implement Heap Sort algorithm in C++ and Report the number of...
In this lab, you will implement Heap Sort algorithm in C++ and Report the number of steps and the CPU running time in a table, please show the code and output Approximation the constant c in the complexity of heap sort (cnlgn) by inspecting the results For each algorithm, and for each n = 100, 200, 300, 400, 500, 1000, 4000, 10000, measure its running time and number of steps when the input is (1) already sort, i.e. n, n-1,...
For this Lab you have to implement a classBuilder. Your Builder classshould have instance...
For this Lab you have to implement a classBuilder. Your Builder class should have instance variable name. , Supply a constructor method for your Builder class and the following methods: getName(), makeRow(int n, String s), printPyramid(int n, String s).Examining the problem, we need to create aBuilder class, declare Builderclass as followspublic class Builder { }Inside the Builder class, declare aString variable called name.Step 3: Defining the constructors:Remember that the purpose of a constructor is to assign valid values to all the data members.public Builder (String name) {...
You work in a materials testing lab and your boss tells you to increase the temperature...
You work in a materials testing lab and your boss tells you to increase the temperature of a sample by 44.7 ∘C∘C . The only thermometer you can find at your workbench reads in degrees Fahrenheit. If the initial temperature of the sample is 62.3 ∘F∘F, what is its temperature in degrees Fahrenheit when the desired temperature increase has been achieved? Express your answer in degrees Fahrenheit to three significant figures.
System Administration Linux/Unix This lab is for you to research and implement old school DNS for...
System Administration Linux/Unix This lab is for you to research and implement old school DNS for your virtualized environment Currently, if you tried to ping your server01 by IP address (192.168.10.11), you would receive a response. If you tried to ping using its hostname "server01", it would result in "ping: hostname: Temporary failure in name resolution" 1) Research how and where to implement 2) Create the following entries: 192.168.10.1 router 192.168.10.11 SRV1 192.168.10.12 SRV2 192.168.10.13 client 3) Ensure these hostnames...
C++ Data Structures: Implement a Stack and a Queue using Linked list In this lab you...
C++ Data Structures: Implement a Stack and a Queue using Linked list In this lab you will implement the functionality of a stack and a queue using a linked list. Your program must use of the declaration of the Stack and Queue class in Stack.h and Queue.h You have to implement the functionalities of queue (enq, deq, displayQueue) in a file called Queue.cpp. All the functions in Queue.cpp should follow the prototypes declared in Queue.h. Your code should make use...
lab requires you to use Oracle VIEW to implement a virtual database on DBSEC schema, for...
lab requires you to use Oracle VIEW to implement a virtual database on DBSEC schema, for example, on CUSTOMER table. Your task is to develop a single SQL script that will perform all the following tasks: Table created for this assignment is listed below: create table CUSTOMER_VPD( SALES_REP_ID NUMBER(4), CUSTOMER_ID NUMBER(8) NOT NULL, CUSTOMER_SSN VARCHAR(9), FIRST_NAME VARCHAR(20), LAST_NAME VARCHAR(20), ADDR_LINE VARCHAR(40), CITY VARCHAR(30), STATE VARCHAR(30), ZIP_CODE VARCHAR(9), PHONE VARCHAR(15), EMAIL VARCHAR(80), CC_NUMBER VARCHAR(20), CREDIT_LIMIT NUMBER, GENDER CHAR(1), STATUS CHAR(1), COMMENTS...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT