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 >
<p style="margin:5px 0 5px;color:blue;font-size:18px;">Topper to current</p>
<input type="text" value="1000">
<input type="text" value="">
<input type="text" value="">
<h2 ></h2>
</div>
CodePudding user response:
The issue is because you're using val()
, and only input
elements have values. To show the output in the h2
use the text()
method.
In addition, I'd suggest separating the selectors, otherwise your code will attempt to add a value
to the h2
and a text node to the input
, 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.
$(document).on("input", ".ChangeCalulator", (e) => {
let $formContainer = $(e.target).closest('.section')
let first = Number($formContainer.find('.CalcFrom').val());
let second = Number($formContainer.find('.CalcTo').val());
let result = ((second - first) / first * 100).toFixed(2);
$formContainer.find('input.CalcResult').val(result);
$formContainer.find('h2.CalcResult').text(result);
});
.section p {
margin: 5px 0 5px;
color: blue;
font-size: 18px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div >
<p>Topper to current</p>
<input type="text" value="1000">
<input type="text" value="">
<input type="text" value="">
<h2 ></h2>
</div>