首页 > 解决方案 > 使用 Ajax 进行乘法运算

问题描述

我想将单价乘以文本框中的数量,并且在我更改文本框的值时它需要不断变化。

<div>
    <label id="" name="price" class="unitprice"><?php echo "Price: <label id = hprice> LKR Rs ".$price.".00 </label> /item" ?></label>
</div>

<label id="lbl"> Quantity:</label>

<div class="quantity buttons_added" id="qtybox">
  <input type="button" value="-" class="minus" id= "minus">
  <input type="text" step="1" min="1" max="<?php echo $qty?>" name="quantity" value="1" title="Qty" class="input-text qty text" id="tqty" size="4" pattern="" inputmode="">
  <input type="button" value="+" class="plus" id="plus">
  <label id="pcs"><?php echo "Piece(s) (".$qty. " pieces available)"?></label>
</div>
</br>
<label>Total:</label>
<p id="total"> 0</p>

标签: javascripthtml

解决方案


创建一个文本框,用户将在其中输入数量值,另一个 <div> 用于显示最终价格。

在 keyup 事件的脚本中,它将读取qty文本框的值并将其乘以现在的价格 100,并在 <div> 标签中显示最终价格:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' name='qty' id='qtity'>
<div id='final_price'></div>
<script>
  var price=100;
  $(document).ready(function () {
    $('#qtity').keyup(function () {
        var qty=this.value
        $('#final_price').html(price*qty);
    });
  });
</script>

推荐阅读