javascript - 从动态表单获取数据到javascript并返回计算

标签 javascript php jquery html forms

我有动态添加数据的表格。数据是关于产品名称、多少产品和含税或不含税的价格。

表单添加输入:

这是原来的形式:(动态生成之后:

<div class="row">
        <input type="hidden" name="count" value="1" />
<div class="input_fields_wrap" class="float-left" dir="rtl" align="right" width="900px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <button class="add_field_button">הוסף עוד שורה</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</br>
    <div align="center"> שם המוצר&nbsp; :<input type="text" id="item_name[]" name="item_name[]" />
    &nbsp;כמות המוצר :<input type="number" id="how_much[]"   name="how_much[]" style=" font-size: 12px; line-height: 1.2em; width: 95px;"  />
    &nbsp;עלות המוצר&nbsp; :<input type="number" id="item_price0]" name="item_price[]" onchange="update1(0);" style=" font-size: 12px; line-height: 1.2em; width: 95px;" />
    עלות אחרי מע&quot;מ&nbsp; :<input type="number"  id="item_price_tax[]" name="item_price_tax[0]" onchange="update2(0);" style=" font-size: 12px; line-height: 1.2em; width: 95px;" />
    סכום&nbsp; :<input type="number"  id="item_price_total[]" name="item_price_total[]" onchange="update1(0);"  style=" font-size: 12px; line-height: 1.2em; width: 125px;"/>
&nbsp;&nbsp;   &nbsp;   &nbsp;
   </div>

这是动态 outo 生成:

<SCRIPT>
$(document).ready(function() {
    var max_fields      = 99999; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 0; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
                   $(wrapper).append('<div class="product-item float-clear" style="clear:both;"  align="center">שם המוצר&nbsp; :<input type="text" id="item_name['+x+']" name="item_name['+x+']" />&nbsp;כמות המוצר :<input type="number" id="how_much['+x+']" name="how_much['+x+']"  style=" font-size: 12px; line-height: 1.2em; width: 95px;"  onchange="update1('+x+');"  />&nbsp;עלות המוצר&nbsp; :<input type="number" id="item_price['+x+']"  style=" font-size: 12px; line-height: 1.2em; width: 95px;" name="item_price['+x+']" onchange="update1('+x+');"  /> עלות אחרי מע&quot;מ&nbsp; :<input type="number"  id="item_price_tax['+x+']" style=" font-size: 12px; line-height: 1.2em; width: 95px;" name="item_price_tax['+x+']" onchange="update1('+x+');" />סכום&nbsp; :<input type="number" style=" font-size: 12px; line-height: 1.2em; width: 125px;"  id="item_price_total['+x+']" name="item_price_total['+x+']" onchange="update1('+x+');" /><a href="#" class="remove_field">הסר</a></div>'); //add input box
          }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

</SCRIPT>

现在我想制作一个脚本来填充最后的输入框(我已经写了 onchange="updat1();"但这个函数不工作,我不知道如何传递和正确返回这里它是!:

function update1(x)
{


        var how_much = "#how_much[]";

        var item_price = "#item_price[]";

        var item_price_tax = "#item_price_tax[]";
        var item_price_tax3 = "item_price_tax[]";

        var item_price_total = "#item_price_total[]";
          var item_price_total3 = "item_price_total[]";


      var how_much2 =     document.getElementById("how_much[]").value;
           var item_price2 =   document.getElementById("item_price[]").value;
           var item_price_tax2 =  document.getElementById("item_price_tax[]").value;
         var item_price_total2 =  document.getElementById("item_price_total[]").value;


if((item_price_tax2==0)||(item_price_tax2=='')){

alert(2);

item_price_tax3.value = document.getElementById(item_price2).value * 1.17;
item_price_total3.value=document.getElementById(item_price2).value * 1.17 * how_much2;
item_price_tax[].value=document.getElementById(item_price2).value * 1.17 * how_much2;
item_price_total[].value=document.getElementById(item_price2).value * 1.17 * how_much2;
}

else{
item_price.value3 = document.getElementById(item_price).value * 83%;
item_price_total3.value=document.getElementById(item_price).value  * 83% * how_much;
}
}

</SCRIPT>

需要帮助非常感谢

最佳答案

这里有几件事需要解决。

首先,您的id 不是唯一的。

其次,您使用的是长 javascript document.getElementById(xyz).value 而不是较短的 jQuery 方式 $(xyz).val()

第三,您到处都在使用x 增量器。增量器是个好主意……但是正如您将在下面建议的代码中看到的那样,我没有使用它。它的唯一用途是与 max_fields 进行比较。

第四,您没有使用 classe 来设置元素的样式。一切都是内联的。这使代码更难阅读和维护。

最后,我把你超长的 append() 行放在多行上......这使得代码更容易阅读。 (我还翻译了希伯来语!但这是为了我的理解!)

我所做的所有这些更改有助于理解您的长附加行。
所有这些影响可读性的因素可能是您在计算中迷失方向的原因。

-----
所以...这是我的建议。
您可以在 this Fiddle 中看到它的运行情况。 .

$(document).ready(function() {
    var max_fields   = 99999; //maximum input boxes allowed
    var wrapper      = $(".input_fields_wrap"); //Fields wrapper
    var add_button   = $(".add_field_button"); //Add button ID

    var x = 0; //initlal text box count

    //on add input button click
    $(add_button).click(function(e){
        e.preventDefault();
        var iwrapper = $( "<div class='input_fields_wrap'></div>" ).appendTo( wrapper );

        if(x < max_fields){ //max input box allowed

            //add input box
            $(iwrapper).append('<div class="product-item float-clear" style="clear:both;" align="center">');

            // Product name (hebrew translation)
            $(iwrapper).append('שם המוצר&nbsp; :                <input type="text" class="item_name">');

            // Amount of product (hebrew translation)
            $(iwrapper).append('&nbsp;כמות המוצר :          <input type="number" class="priceInput how_much">');

            // The cost of the product (hebrew translation)
            $(iwrapper).append('&nbsp;עלות המוצר&nbsp; :        <input type="number" class="priceInput item_price">');

            // The cost after VAT (hebrew translation)
            $(iwrapper).append('עלות אחרי מע&quot;מ&nbsp; : <input type="number" class="priceInput item_price_tax" disabled>');

            // Amount (hebrew translation)
            $(iwrapper).append('סכום&nbsp; :                    <input type="number" class="totalInput item_price_total" disabled>');

            // Remove (hebrew translation)
            $(iwrapper).append('                                <a class="remove_field">הסר</a>');
            $(wrapper).append('</div>');

            x++;
        }
    });

    //user click on remove text
    $(wrapper).on("click",".remove_field", function(e){
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    })

    // Your "update1" function improved
    $(".input_fields_wrap").on("change",".how_much, .item_price",function(){

        var how_much = $(this).parent().children(".how_much").val();
        var item_price = $(this).parent().children(".item_price").val();

        if( how_much==0 || item_price==0 ){
            // rests displayed values to zero, user has not finished inputting values.
            $(this).siblings(".item_price_tax").val("");
            $(this).siblings(".totalInput").val("");
        }else{
            // Calculations
            item_price_VAT = item_price * 1.17;
            total = how_much * item_price_VAT;

            // Show calculated amounts
            $(this).siblings(".item_price_tax").val(item_price_VAT);
            $(this).siblings(".totalInput").val(total);
        }
    });
});

注意:我禁用结果输入,因为用户不应该修改这些(在我看来)。这是我应用的 CSS...

.priceInput{
    font-size:12px;
    line-height:1.2em;
    width:95px;
}
.totalInput{
    font-size:12px;
    line-height:1.2em;
    width:125px;
}
.remove_field{        // This one replaces a unuseful href="#"
    text-decoration:underline;
    color:dodgerblue;
    cursor:pointer;
}

奖金
我想知道为什么你在哪里使用这么多 []...
并提出了您可以使用数组保存这些行的想法。

下面是如何在提交函数中创建数组:

// Prepare values into arrays...
var item_name_array=[];
var how_much_array=[];
var item_price_array=[];
var item_price_tax_array=[];
var item_price_total_array=[];

$(".item_name").each(function(i,val){
    item_name_array[i] = $(this).val();
    how_much_array[i] = $(this).sibling(".how_much").val();
    item_price_array[i] = $(this).sibling(".item_price").val();
    item_price_tax_array[i] = $(this).sibling(".item_price_tax").val();
    item_price_total_array[i] = $(this).sibling(".item_price_total").val();
});

关于javascript - 从动态表单获取数据到javascript并返回计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38112351/

相关文章:

javascript - 基于 ASC 和 DESC 顺序中姓氏的排序数组

php - microtime(true) - 无法测量 PHP 脚本执行时间

javascript - jQuery 切换多下拉选择

php - html切换开关按钮单击时会转到另一个页面

php - 上传文件限制

javascript - 在 flex-box 中为动态添加的 flex-item 添加一个按钮

android - 试图将元素保留在页面底部

javascript setHours 日期设置为上一个日期

javascript - 引用内存可供 2 个 Controller 进行通信

javascript - Jquery Document.ready 循环