Convert from Kilometers to Centimeters Using Javascript code with HTML

Here’s the HTML and JavaScript code for a simple Kilometers to centimeters converter:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kilometers to Centimeters Converter</title>
</head>
<body>
<h1>Kilometers to Centimeters Converter</h1>
<label for="km">Enter kilometers:</label>
<input type="number" id="km" required>
<button onclick="convertToCm()">Convert</button>
<p id="result"></p>
<script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

function convertToCm() {
const kilometers = parseFloat(document.getElementById("km").value);
const centimeters = kilometers * 100000; // 1 kilometer = 100,000 centimeters
const resultElement = document.getElementById("result");
resultElement.textContent = `${kilometers} kilometers is equal to ${centimeters.toFixed(2)} centimeters.`;
}

Explanation:

1. HTML:
* The HTML code defines the basic structure of the web page, including a heading, label, input field, button, and a paragraph element to display the result.
* It also includes a script tag referencing an external JavaScript file named “script.js”.

2. JavaScript:
* The `convertToCm` function is triggered when the “Convert” button is clicked.
* It retrieves the value entered in the “km” input field and converts it to a number using `parseFloat`.
* It then calculates the equivalent value in centimeters by multiplying the kilometers by 100,000 (conversion factor).
* Finally, it accesses the “result” paragraph element and updates its content with the converted value, formatted to two decimal places using `toFixed(2)`.