How to Convert from Inches to cm Using Javascript With HTML?

Hello Friends Today, through this tutorial, I will tell you How to Convert inches to Centimeters Using JavaScript With HTML.Here’s the HTML and JavaScript code for an Inches to cm converter:

inchestocm.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inches to Centimeters Converter using Javascript</title>
</head>
<body>
<h1>Inches to Centimeters Converter using Javascript</h1>
<p>Enter a value in inches:</p>
<input type="number" id="inchesInput" placeholder="Inches">
<button onclick="convertToCm()">Convert</button>
<p id="result"></p>
<script>
function convertToCm() {
const inches = document.getElementById("inchesInput").value;
const cm = inches * 2.54; // Conversion factor
const result = document.getElementById("result");
result.textContent = `${inches} inches is equal to ${cm.toFixed(2)} centimeters.`;
}
</script>
</body>
</html>

Explanation

1. Defines the basic structure with a heading, input field, button, and a paragraph element to display the result.
2. Defines the `convertToCm` function.
3. Retrieves the value entered in the `inchesInput` field using `document.getElementById`.
4. Converts the inches to centimeters using the conversion factor (1 inch equals 2.54 centimeters).
5. Retrieves the `result` element where the converted value will be displayed.
6. Uses template literals and string interpolation to format the output and display the converted value with two decimal places using `toFixed(2)`.

This code provides a simple and functional way to convert inches to centimeters using HTML and JavaScript.