用javascript计算

时间:2015-07-14 16:53:23

标签: javascript

好吧所以我有这个html,我想计算数量* pricePerItem与我输入的数字。 Thx提前。

书店

<h3>Please select your books</h3>
<div>
    <label for="quantity">Quantity</label>
    <input type="text" id="quantity" />
</div>
<div>
    <label for="quantity">Price per item</label>
    <input type="text" id="pricePerItem" />
</div>
<div>
    <button>View price</button>
</div>
<div class="payment-info">
    Amount to pay: <span id="total"></span>
</div>


$(document).ready(function() {
var quantity = $("#quantity");
var price = $("#pricePerItem");

$("total").text(price * quantity);
});`

3 个答案:

答案 0 :(得分:0)

$(document).ready(function() {

$('button').on('click',function(){
  var quantity = parseFloat($("#quantity").val());
var price = parseFloat($("#pricePerItem").val());
$('#total').html(price * quantity);
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Please select your books</h3>
<div>
    <label for="quantity">Quantity</label>
    <input type="text" id="quantity" />
</div>
<div>
    <label for="quantity">Price per item</label>
    <input type="text" id="pricePerItem" />
</div>
<div>
    <button>View price</button>
</div>
<div class="payment-info">
    Amount to pay: <span id="total"></span>
</div>

答案 1 :(得分:0)

代码的问题在于

var quantity = $("#quantity");

您只是选择变量中的html输入元素而不是获取输入元素的值。

此外,您还必须在按钮上添加event listener,以便在每次对input元素中的值进行任何更改时获取值。

请查找随附的代码

$(document).ready(function(){
    $('button').click(function(){
        var quantity = $('#quantity').val()
        var price = $('#pricePerItem').val()
        var total = quantity*price;        
        $('#total').text(total);    
    });
});

答案 2 :(得分:0)

你可以试试这个

HTML

    <h3>Please select your books</h3>
    <div>
      <label for="quantity">Quantity</label>
      <input type="text" id="quantity" />
    </div>
    <div>
      <label for="quantity">Price per item</label>
      <input type="text" id="pricePerItem" />
    </div>
    <div>
      <button onclick="calculateTotal();">View price</button>
    </div>
    <div class="payment-info">Amount to pay: <span id="total"></span>
    </div>

JS

   function calculateTotal() {
        var quantity = $("#quantity").text();
        var price = $("#pricePerItem").text();

        $("#total").text(quantity * price);
    }

http://plnkr.co/edit/pctAxRZ80Zr8Q8e0zm2g?p=info