Hello Friends Today, through this tutorial, I will tell you Convert from Kilometers to Meters Using Javascript script code with html.
Here’s the HTML and JavaScript code for a Kilometers to Meters 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 Meters Converter</title> </head> <body> <h1>Kilometers to Meters Converter</h1> <p>Enter the value in kilometers:</p> <input type="number" id="kilometers" placeholder="Kilometers"> <button onclick="convertKilometersToMeters()">Convert</button> <p id="result"></p> <script src="script.js"></script> </body> </html>
JavaScript (script.js):
function convertKilometersToMeters() { const kilometers = parseFloat(document.getElementById("kilometers").value); const meters = kilometers * 1000; // 1 kilometer = 1000 meters const resultElement = document.getElementById("result"); if (!isNaN(kilometers)) { resultElement.textContent = `${kilometers} kilometers is equal to ${meters} meters.`; } else { resultElement.textContent = "Please enter a valid number."; } }
Explanation:
1. HTML:
* Defines the basic structure of the web page including title, heading, input field, button, and result paragraph.
* Links the JavaScript file named “script.js” to be executed.
2. JavaScript (script.js):
* Defines a function `convertKilometersToMeters`.
* Retrieves the value entered in the “kilometers” input field using `document.getElementById`.
* Converts the value to a number using `parseFloat`.
* Calculates the equivalent meters by multiplying kilometers by 1000 (conversion factor).
* Retrieves the element with the ID “result” using `document.getElementById`.
* Checks if the entered value is a valid number using `isNaN` (is Not a Number).
* If valid, displays the conversion result using string interpolation.
* If invalid, displays an error message.
This code demonstrates a simple conversion tool using HTML and JavaScript. You can further enhance it by adding features like displaying the conversion factor or allowing users to choose from different units.