Reputation: 407
I'm trying to multiply the annual litres (#save-lt) by the average fuel price (#usd). The What you save per year in litres is working, any ideas I'm guessing a variable is needed? I'm still learning jquery any help appreciated!
jQuery(document).ready(function() {
jQuery('#litres').keyup(function() {
jQuery('#save-lt').text(parseInt(jQuery('#litres').val()) * 52 / 100 * 12);
});
jQuery('#usd').keyup(function() {
jQuery('#save-usd').text(parseInt(jQuery('#save-lt').val()) * ('#usd').val()));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Enter you fuel consumption per week in litres?</h4>
<input type="text" placeholder="Litres (LT)" id="litres" />
<h4>Enter the average price you pay for a litre of fuel in USD?</h4>
<input type="text" class="fuel" placeholder="USD ($)" id="usd" />
<h2>Annual Savings</h2>
<h4>What you save per year in litres (LT):</h4>
<h3 value="0" id="save-lt">0</h3>
<h3>LT</h3>
<h4>What you save per year in USD ($):</h4>
<h3>$</h3>
<h3 value="0" id="save-usd">0</h3>
Upvotes: 1
Views: 26
Reputation: 337560
You're missing the $
prefix on ('#usd')
and the #save-usd
element is a h3
so it doesn't have a value
to be read using val()
. Use text()
for that instead. The extra )
in the second keyup
logic should also be removed.
Note that you can alias the $
variable within the jQuery document.ready handler to avoid needing to use jQuery
references every and make your code less verbose and easier to read. In addition you can use the input
event instead of keyup
to also handle events fired by mouse input, such as copy+paste using context menus. Finally you can omit the parseInt()
call as the value will be coerced using Number
when you perform a mathematical operation on it - as you do with the *
operator.
With all that said, try this:
jQuery($ => {
$('#litres').on('input', () => $('#save-lt').text($('#litres').val() * 52 / 100 * 12));
$('#usd').on('input', () => $('#save-usd').text($('#save-lt').text() * $('#usd').val()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Enter you fuel consumption per week in litres?</h4>
<input type="text" placeholder="Litres (LT)" id="litres" />
<h4>Enter the average price you pay for a litre of fuel in USD?</h4>
<input type="text" class="fuel" placeholder="USD ($)" id="usd" />
<h2>Annual Savings</h2>
<h4>What you save per year in litres (LT):</h4>
<h3 id="save-lt">0</h3>
<h3>LT</h3>
<h4>What you save per year in USD ($):</h4>
<h3>$</h3>
<h3 id="save-usd">0</h3>
Upvotes: 1