Hello Friends Today, through this tutorial, I will tell you Convert from Kilometers to Miles Using Javascript script code with html. Here’s the HTML and JavaScript code for a Kilometers to Miles 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 Miles Converter</title> </head> <body> <h1>Kilometers to Miles Converter</h1> <p>Enter a value in kilometers:</p> <input type="number" id="kmInput" placeholder="Kilometers"> <button onclick="convertKmToMiles()">Convert</button> <p id="result"></p> <script src="script.js"></script> </body> </html>
JavaScript (script.js):
function convertKmToMiles() { const kilometers = document.getElementById("kmInput").value; const miles = kilometers * 0.621371; // Conversion factor const result = document.getElementById("result"); result.textContent = `${kilometers} kilometers is equal to ${miles.toFixed(2)} miles.`; }
Explanation:
1. The HTML code defines the basic structure of the page with headings, input fields, a button, and a paragraph element to display the result.
2. The JavaScript code is linked in a separate file named `script.js`.
3. The `convertKmToMiles` function is defined.
4. It retrieves the value entered in the `kmInput` field using `document.getElementById`.
5. It converts the kilometers to miles using the conversion factor (1 kilometer is equal to 0.621371 miles).
6. It retrieves the `result` element where the converted value will be displayed.
7. It 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 kilometers to miles using HTML and JavaScript.