Hello Friends Today, through this tutorial, I will tell you Convert from Kilometers to Yards Using Javascript script code with html.
Here’s the HTML and JavaScript code for a Kilometers to Yards 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 Yards Converter</title> </head> <body> <h1>Kilometers to Yards Converter</h1> <label for="km-input">Enter kilometers:</label> <input type="number" id="km-input" placeholder="0"> <button onclick="convertKmToYards()">Convert</button> <p id="result"></p> <script src="script.js"></script> </body> </html>
JavaScript (script.js):
function convertKmToYards() { const kilometers = document.getElementById("km-input").value; const yards = kilometers * 1093.61; // Conversion factor: 1 kilometer = 1093.61 yards const resultElement = document.getElementById("result"); if (isNaN(kilometers)) { resultElement.textContent = "Please enter a valid number."; } else { resultElement.textContent = `${kilometers} kilometers is equal to ${yards.toFixed(2)} yards.`; } }
Explanation:
1. HTML:
* The HTML code defines the basic structure of the web page, including a heading, labels, input fields, a button, and a paragraph element to display the result.
* It also includes a script tag that references an external JavaScript file named `script.js`.
2. JavaScript:
* The `convertKmToYards` function is triggered when the “Convert” button is clicked.
* It retrieves the value entered in the “km-input” field using `document.getElementById`.
* It performs the conversion by multiplying the kilometers by the conversion factor (1093.61).
* It retrieves the “result” element using `document.getElementById`.
* It checks if the entered value is a valid number using `isNaN`.
* If it is not a number, an error message is displayed.
* If it is a number, the converted value is formatted to two decimal places using `toFixed(2)` and displayed along with the original value and units.
How to use:
1. Save the HTML code as `index.html` and the JavaScript code as `script.js` in the same directory.
2. Open `index.html` in your web browser.
3. Enter a value in kilometers in the input field.
4. Click the “Convert” button.
5. The result, showing the equivalent value in yards, will be displayed in the paragraph below the button.