Hello Friends Today, through this tutorial, I will tell you How to Convert centimeters (cm) to meters Using JavaScript With HTML.Here's how to convert centimeters (cm) to meters using JavaScript within an HTML page:
Index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CM to Meters Converter</title> </head> <body> <h1>CM to Meters Converter</h1> <label for="cm_value">Enter value in centimeters (cm):</label> <input type="number" id="cm_value" name="cm_value" required> <br> <button type="button" onclick="convert()">Convert</button> <p id="result"></p> <script src="script.js"></script> </body> </html>JavaScript (`script.js`).
function convert() {
// Get the CM value from the input field
const cmValue = document.getElementById("cm_value").value;
// Check if a value was entered
if (!cmValue) {
alert("Please enter a value in centimeters.");
return;
}
// Validate the input (optional)
if (isNaN(cmValue)) {
alert("Please enter a valid numerical value.");
return;
}
// Conversion factor (1 cm = 0.01 meters)
const cmToMeters = 0.01;
// Calculate meters
const meters = cmValue * cmToMeters;
// Display the results
const result = `CM value: ${cmValue}<br>Meters: ${meters.toFixed(2)}`; // Format to 2 decimal places
document.getElementById("result").innerHTML = result;
}
Explanation.
1. HTML.
- This HTML structure is similar to the previous examples, using a button to trigger the conversion with JavaScript.
2. JavaScript (`script.js`).
- The `convert` function is called when the "Convert" button is clicked.
- It retrieves the user input from the `cm_value` input field.
- It checks if a value is entered and displays an alert if not.
- You can optionally add input validation to check for numerical values.
- It defines a conversion factor of 1 cm = 0.01 meters.
- It calculates the meters by multiplying the cm value with the conversion factor.
- It constructs a string containing the original CM value and the converted meters value, formatted to two decimal places using `toFixed(2)`.
- It updates the content of the `result` paragraph element using `innerHTML` to display the final result.