多次使用输入

时间:2015-04-01 11:57:50

标签: javascript jquery

我有三个input字段type:number,当按下按钮时,所有字段都会被单独调用。 例如,我点击button1然后会出现dialog1,依此类推。 我想在后面的代码(jQuery)中做的是从数字输入中获取值并将其放在<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: &euro; " + total);
  });

这样可行,但它会更改所有.total-price div ...我可以使用id,但我不在id="amount1"id="amount2 &#34;,id="amount3"

那太乱了。

4 个答案:

答案 0 :(得分:1)

尝试.siblings()并将$('.amount').val()更改为$(this).val()(以获取所引用输入的值)

  $(".amount").change(function(){
    price = 9.99;
    amount = $(this).val()
    total = price * amount;
    $(this).siblings(".total-price").html("Totaal: &euro; " + total);
  });

$(".amount").change(function(){
    price = 9.99;
    amount = $(this).val()
    total = price * amount;
    $(this).siblings(".total-price").html("Totaal: &euro; " + 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>

答案 1 :(得分:1)

更改行

amount = $(".amount").val()
$(".total-price").html("Totaal: &euro; " + total);

amount = $(this).val(); 
$(this).parent().find(".total-price").html("Totaal: &euro; " + total);

答案 2 :(得分:1)

在jquery中使用.next()

$(this).val(); //to get current input 
$(this).next().html("Totaal: &euro; " + total);

答案 3 :(得分:1)

由于输入和div处于同一级别,您可以使用jQuery中的siblings()

$(".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: &euro;"+total);
});

当您在元素内部时,您需要使用this来引用该元素。