【问题标题】:Calculate sum of select fields in a dynamic form以动态形式计算选择字段的总和
【发布时间】:2016-03-08 21:46:06
【问题描述】:

我有一个问题,它已经困扰我好几天了,我有一个动态选择字段,用户从数据库中选择一种成分,如果他想添加更多成分,他只需点击“添加”按钮,然后创建了另一个选择字段,所有选择字段都显示其名称和价格(作为文本),并且有一个输入文本字段(basePrice)应该具有创建的每个选择的总和

选择字段

   <select name="ingredienteId[]" id="ingredienteId"  onchange="DoMath()">
          <?php foreach($ingredientes as $ingrediente) {
       $essaEhATorta = $torta['ingredienteId'] == $ingrediente['id'];
        $selecao = $essaEhATorta ? "selected='selected'" : "";
        ?> 
            <option value="<?=$ingrediente['id']?>" <?=$selecao?>>
 <?=$ingrediente['nome']?> <?=$ingrediente['price']?>  
        </option>
                              <?php } ?> 
    </select>

动态选择字段

$('#add').click(function() {
var newSelect = $('<label>Ingrediente</label> <select name="ingredienteId[]" id="ingredienteId" class="form-control"> <?php foreach($ingredientes as $ingrediente) {$essaEhATorta = $torta["ingredienteId"] == $ingrediente["id"];$selecao = $essaEhATorta ? 'selected="selected"' : "";?> <option value="<?=$ingrediente["id"]?>" <?=$selecao?>><?=$ingrediente["nome"]?><?=$ingrediente["preco"]?>   </option><?php } ?> </select>')
$('#notas').append(newSelect);
});

basePrice 输入文本字段

<input class="form-control" type="text" value="<?=$torta['precoBase']?>" name="precoBase" id="basePrice"/>

正如我之前所说,选择选项将产品的名称/价格作为文本&lt;?=$ingrediente['nome']?&gt;&lt;?=$ingrediente['price']?&gt;,所以我只想要价格我想出了这个代码:

DoMath()

function DoMath(){

var e = document.getElementById("ingredienteId");
var finalPrice= e.options[e.selectedIndex].text;
var noLetterPrice = finalPrice.replace(/[^0-9,"."]/g,'');
var result = parseFloat(noLetterPrice);
document.getElementById("basePrice").value = result;

View

我的部分代码是葡萄牙语,但我希望你们能理解

您可以看到转换部分有效,但我不知道如何使总和部分有效,我尝试了一些方法,但似乎没有任何效果

【问题讨论】:

  • 请先删除短裤标签,但无法在您的 html 结构中找到#add

标签: javascript php jquery mysql arrays


【解决方案1】:

Instead of taking value and find price using regex will create issue when options names contains some digital values.

在 Jquery 中,我们可以为任何字段提供任何自定义属性。因此,在选项中的自定义属性之一中获取该价格。这将非常容易。

试试下面的代码

选择字段 HTML 结构

<input type="button" name="add" id="add" value="Add" />
<input class="form-control" type="text" value="0" name="precoBase" id="basePrice"/>
<div id="notas">
    <div id="ing_div">
        <label>Ingrediente</label> 
        <select name="ingredienteId[]" class="baseingredient">
            <option value="" ing-price="0"> Select Price</option>
            <?php
            foreach ($ingredientes as $ingrediente) {
                $essaEhATorta = false;
                $selecao = $essaEhATorta ? "selected='selected'" : "";

                ?> 
                <option value="<?= $ingrediente['id'] ?>" <?= $selecao ?> ing-price="<?= $ingrediente['price'] ?>">
                    <?= $ingrediente['nome'] ?> <?= $ingrediente['price'] ?>  
                </option>
            <?php } ?> 
        </select>
    </div>
</div>

在上面的 HTML 中,我在 ing-price 属性中采用了价格。

Javascript 代码

<script>
   $(document).on("click",'#add',function() {
        var newSelect = $('#ing_div').clone();
        newSelect.find("select[name='ingredienteId[]'").val();
        $('#notas').append(newSelect);
    });

    $(document).on("click",".baseingredient",function(){
        tot=0;
        $(".baseingredient").each(function(){
            tot+=parseFloat($(this).find("option:selected").attr("ing-price"));

        })
        $("#basePrice").val(tot);
    });
</script>

【讨论】:

  • 嘿伙计很棒的代码,但是 sum 部分在这里仍然不起作用自定义属性确实比正则表达式更好,但我不得不将`$essaEhATorta = false;`更改为我的旧@987654323 @ 因为这就是我将成分 ID 与另一个表连接的方式,所以我尝试了 var option = $('option:selected', this).attr('ing-price'); tot+=parseFloat(option);,但它在 basePrice 输入上给出了 NaN 任何提示?
  • 嘿,我现在才知道,parseFloat 传递了 NaN 和 idk 为什么,我尝试了 parseInt,它工作了哈哈
【解决方案2】:

You can use each() inside your script, which totals the cost of ingredients, when a select field has been changed.

我们必须为您的select 输入分配第一个class 标签。

<select class="ing" .....

将它也添加到“待附加”select 输入中。

var newSelect = $('<label>Ingrediente</label> <select class="ing" .....

使用each(),我们可以遍历所有带有class标签ingselect字段:

$(document).on("change", ".ing", function(){ /* WHEN A SELECT FIELD HAS CHANGED */

  var total = 0;
  $('.ing').each(function() { /* RUN ALL SELECT FIELD */
    total = total + parseInt($(this).val()); /* SUM UP ALL */
  });
  $("#basePrice").val(total); /* CHANGE THE VALUE OF BASE PRICE FIELD */

});

我更喜欢拥有

$(document).on("change", ".ing", function(){

而不是你以前的

function DoMath(){

由于动态附加的select 字段而起作用。

这是一个jsfiddle(示例),您可以查看。

【讨论】:

    【解决方案3】:

    您应该使用.on() 而不是.click()onchange,如下所示:

    $(document).on('click','#add',function(){
        var newSelect = $('<label>Ingrediente</label> <select name="ingredienteId[]" id="ingredienteId" class="form-control"> <?php foreach($ingredientes as $ingrediente) {$essaEhATorta = $torta["ingredienteId"] == $ingrediente["id"];$selecao = $essaEhATorta ? 'selected="selected"' : "";?> <option value="<?=$ingrediente["id"]?>" <?=$selecao?>><?=$ingrediente["nome"]?><?=$ingrediente["preco"]?>   </option><?php } ?> </select>')
        $('#notas').append(newSelect);
    });
    
    $(document).on('change','#ingredienteId',function(){
        // calculate sum of every select fields
    });
    

    您使用的click() 绑定称为“直接”绑定,它只会将处理程序附加到已存在的元素。它不会绑定到将来创建的元素。为此,您必须使用on() 创建一个“委托”绑定。

    来自documentation of .on()

    委托事件的优点是它们可以处理来自后代元素的事件,这些事件会在以后添加到文档中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多