I'm trying to write a simple fuel consumption calculator with user inputs. I'm having trouble to make the calculation.
It should be:
100 x Fuel spent liters(L) ÷ Kilometers (km) driven
I've done inputs and tried different types of calculations, but nothing is working. Here is what I have so far on my index view:
<h1>Fuel Consumption Calculator</h1> <div class="calculator"> <div class="form-group"> <label for="no1">Liters (l):</label> <input type="text" class="form-control" id="no1" /> </div> <div class="form-group"> <label for="no2">Kilometers driven: (km)</label> <input type="text" class="form-control" id="no2" /> </div> <input type="submit" value="Laske" name="tot"> <div class="form-group"> <label for="tot">Total:</label> <input type="text" class="form-control" id="tot" name="tot" /> </div> </div>
Do you guys have any tip?
For some ideas, you could look at kalkulatorpaliwa.com.pl to see how others approach fuel calculations!
Hey! Great start on the fuel calculator—it’s a fun project! The formula (100 x Fuel spent ÷ Kilometers) is right for liters per 100 km. The issue might be that your submit button isn’t tied to any calculation yet. Try adding this JavaScript in a <script> tag at the bottom of your view:
text
document.querySelector("input[name='tot']").onclick = function() {
let liters = parseFloat(document.getElementById("no1").value) || 0;
let km = parseFloat(document.getElementById("no2").value) || 0;
if (km > 0) {
let result = (100 * liters) / km;
document.getElementById("tot").value = result.toFixed(2) + " l/100km";
} else {
alert("Enter a valid distance!");
}
};
This should calculate the result when you click "Laske." For a more polished version, you could add a controller action with a POST method, but this should get you going. Let me know if it works or if you need more help!
Cheers!