Reputation: 1402
I have three input
fields type:number
which all are called separately when pushed on a button.
For instance, I click on button1
then dialog1
appears and so on..
What I want to do in code behind (jQuery
) is to get the value from the number input and place it in <div class="total-price"></div>
<div id="dialog1">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
<div id="dialog2">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
<div id="dialog3">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
jQuery
$(".amount").change(function(){
price = 9.99;
amount = $(".amount").val()
total = price * amount;
$(".total-price").html("Totaal: € " + total);
});
This works fine, but it changes ALL the .total-price
divs... I could work with id
but I'm not here for id="amount1"
, id="amount2
", id="amount3"
That's so messy.
Upvotes: 0
Views: 99
Reputation: 2300
change the lines
amount = $(".amount").val()
$(".total-price").html("Totaal: € " + total);
to
amount = $(this).val();
$(this).parent().find(".total-price").html("Totaal: € " + total);
Upvotes: 1
Reputation: 15393
use .next()
in jquery
$(this).val(); //to get current input
$(this).next().html("Totaal: € " + total);
Upvotes: 1
Reputation: 33618
Try .siblings()
and also change $('.amount').val()
to $(this).val()
(to get the value of input being referred to)
$(".amount").change(function(){
price = 9.99;
amount = $(this).val()
total = price * amount;
$(this).siblings(".total-price").html("Totaal: € " + total);
});
$(".amount").change(function(){
price = 9.99;
amount = $(this).val()
total = price * amount;
$(this).siblings(".total-price").html("Totaal: € " + total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dialog1">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
<div id="dialog2">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
<div id="dialog3">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
Upvotes: 1
Reputation: 1086
As the input and the div are in the same level, you can use siblings()
from jQuery.
$(".amount").change(function() {
price = 9.99;
amount = $(this).val(); //This will get the value from the current input
total = price * amount;
$(this).siblings(".total-price").html("Total: €"+total);
});
You need to use this
when you are inside an element to refer that element.
Upvotes: 1