Convert from Kilometers to Inches Using Javascript code with HTML

Here’s the HTML and JavaScript code for a converter that converts kilometers to inches:

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 Inches Converter</title>
</head>
<body>
<h1>Kilometers to Inches Converter</h1>
<label for="km">Enter kilometers:</label>
<input type="number" id="km" placeholder="0">
<button onclick="convertToInches()">Convert</button>
<p id="result"></p>
<script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

function convertToInches() {
const kilometers = parseFloat(document.getElementById("km").value);
const inches = kilometers * 39370.0787; // Conversion factor
const resultElement = document.getElementById("result");
if (isNaN(kilometers)) {
resultElement.textContent = "Please enter a valid number.";
} else {
resultElement.textContent = `${kilometers} kilometers is equal to ${inches.toFixed(2)} inches.`;
}
}

Explanation:

1. HTML:
* The basic HTML structure defines headings, labels, an input field for the kilometers value, a button to trigger the conversion, and a paragraph element to display the result.
* It includes a reference to an external JavaScript file named “script.js” where the conversion logic resides.

2. JavaScript (script.js):
* The `convertToInches` function is triggered when the “Convert” button is clicked.
* It retrieves the value entered in the kilometers input field using `document.getElementById(“km”).value`.
* It parses the value to a number using `parseFloat` to ensure proper calculations.
* The conversion factor (1 kilometer = 39370.0787 inches) is used to calculate the equivalent value in inches.
* The function checks if the input is a valid number using `isNaN`. If not, it displays an error message.
* If the input is valid, it displays the converted value with two decimal places using `toFixed(2)`.
* The result is displayed in the paragraph element with ID “result”.

Note: This script assumes a one-way conversion from kilometers to inches. You can modify it to be bi-directional by adding another input field and logic for converting inches to kilometers.