You can create a Watts/Volts/Amps/Ohms calculator using JavaScript by allowing the user to input any two values and then calculating the other two based on Ohm’s law and power formula. Here’s how you can implement it:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Watts / Volts / Amps / Ohms Calculator</title>
</head>
<body>
<h1>Watts / Volts / Amps / Ohms Calculator</h1>
<label for="watts">Watts (W): </label>
<input type="number" id="watts">
<br>
<label for="volts">Volts (V): </label>
<input type="number" id="volts">
<br>
<label for="amps">Amps (A): </label>
<input type="number" id="amps">
<br>
<label for="ohms">Ohms (Ω): </label>
<input type="number" id="ohms">
<br>
<button onclick="calculate()">Calculate</button>
<br>
<p id="result"></p>
<script>
function calculate() {
let watts = document.getElementById('watts').value;
let volts = document.getElementById('volts').value;
let amps = document.getElementById('amps').value;
let ohms = document.getElementById('ohms').value;
let result = '';
// Validate input
if (isNaN(watts) && isNaN(volts)) {
result = "Please enter values for Watts and Volts.";
} else if (isNaN(volts) && isNaN(amps)) {
result = "Please enter values for Volts and Amps.";
} else if (isNaN(amps) && isNaN(ohms)) {
result = "Please enter values for Amps and Ohms.";
} else if (isNaN(ohms) && isNaN(watts)) {
result = "Please enter values for Ohms and Watts.";
} else {
// Calculate missing values
if (isNaN(watts)) {
watts = volts * amps;
} else if (isNaN(volts)) {
volts = watts / amps;
} else if (isNaN(amps)) {
amps = watts / volts;
} else if (isNaN(ohms)) {
ohms = volts / amps;
}
// Display result
result = `Watts: ${watts} W, Volts: ${volts} V, Amps: ${amps} A, Ohms: ${ohms} Ω`;
}
document.getElementById('result').textContent = result;
}
</script>
</body>
</html>
In this example:
1. We have input fields for Watts, Volts, Amps, and Ohms, along with a “Calculate” button.
2. When the user clicks the “Calculate” button, the `calculate()` function is called.
3. The function retrieves the values from the input fields and validates them.
4. Based on the provided values, the missing values are calculated using the appropriate formulas.
5. The result is displayed to the user.