I have multiple forms on my page with the same input. I'd like to multiple some value from inputs. Now my code working only for first form inputs.
$("#quantity").each(function () {
var $final_price = $('#final_price');
$("#quantity").on('keyup', function (e) {
var quantity = parseFloat($(this).val());
var product_price = parseFloat($("input[name='product_price']").val(), 10);
$final_price.val(quantity * product_price);
});
});
CodePudding user response:
Your HTML should be
<input type="number" name="quantity" class="quantity" required="required">
Your Javascript should be
$(".quantity").on('keyup', function (e) {
var quantity = parseFloat($(this).val());
var product_price = parseFloat($("input[name='product_price']").val(), 10);
$final_price.val(quantity * product_price);
});
CodePudding user response:
Your code only works on the first form because you are targeting an id, i.e. #quantity
, and you can only have one id per page.
What you need to do is use classes, e.g.:
$('.quantity').each(function(index, value) {
var $input = $(value);
console.log($input.val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" class="quantity" value="232" />
</form>
<form>
<input type="text" class="quantity" value="765" />
</form>
<form>
<input type="text" class="quantity" value="987" />
</form>