I have a percentage calculator which is working. However the result is showing only in my input
. It is not showing in my h2
. I want the result to display in both the input
and h2
. Is this possible?
$(document).on("change keyup blur live", ".ChangeCalulator", function() { // For:- = Topper To Current %
let formContainer = $(this).closest('.section')
var first = Number($(formContainer).find('.CalcFrom').val()); // = Topper Price
var second = Number($(formContainer).find('.CalcTo').val()); // = Current Price
var minus = second - first; // 2000 - 1000 = {1000 = minus}
var divide = (minus / first); // 1000 / 1000 = 1
var multiply = divide * 100; // 1 * 100 = 100%
$(formContainer).find('.CalcResult').val(Number(multiply).toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="section">
<p style="margin:5px 0 5px;color:blue;font-size:18px;">Topper to current</p>
<input type="text" class="ChangeCalulator CalcFrom" value="1000">
<input type="text" class="CalcTo ChangeCalulator" value="">
<input type="text" class="CalcResult" value="">
<h2 class="CalcResult"></h2>
</div>
2
Answers
The issue is because you’re using
val()
, and onlyinput
elements have values. To show the output in theh2
use thetext()
method.In addition, I’d suggest separating the selectors, otherwise your code will attempt to add a
value
to theh2
and a text node to theinput
, which is invalid.Finally, use the
input
event instead of multiple events you bound to, and also don’t double-wrap your jQuery objects, it’s a waste.