简体   繁体   English

遍历html选择和输入

[英]Looping through html selects and inputs

I'm creating this application where you get the total price of all items selected based on user selection. 我正在创建此应用程序,您将在其中获得根据用户选择选择的所有项目的总价。 I have to get the summation of the results of each row where each row is actually composed by 2 selects (ID/item) and one input for quantity. 我必须获得每一行结果的总和,其中每一行实际上是由2个选择(ID /项)和一个数量输入组成的。 Thing is, I added an additional function where you can keep adding rows depending on the user. 事情是,我添加了一个附加功能,您可以根据用户不断添加行。 Therefore, I need to create a loop function to check each row selection and sum all these up and throw the result to the html -- and this where I'm stuck. 因此,我需要创建一个循环函数来检查每个行的选择,并将所有这些求和加起来,然后将结果扔到html上,这就是我遇到的问题。

BTW, the price of the item selected will be based on a variable array. 顺便说一句,所选商品的价格将基于可变数组。 After fetching the price, you multiply that by the quantity then you get the total price for one row. 提取价格后,将其乘以数量即可得到一行的总价格。 The total price is the summation of all rows where there's complete data. 总价是有完整数据的所有行的总和。

Your help is greatly appreciated. 非常感谢您的帮助。

To explain it better for you, here's how it looks like and here's a jsfiddle : 为了更好地为您解释它,这是它的外观,这是一个jsfiddle

<div class="complrow">
    <div class="span4">ID</div>
    <div class="span4">Fruit</div>
    <div class="span4">Quantity</div>    
</div>
<div class="complrow">
    <button id="addrow">Add Rows</button><br/>
</div>
<button id="thisisit">Check!</button><br/>
<div>
   <p>Total Price:</p><br/>
   <p id="try"></p>
</div>

with a bit of CSS: 带有一些CSS:

#try{
  margin-top:20px;
  border: 1px solid black;
}

.span4{
    display: inline-block;
        width: 100px;
        margin-left: 10%;
}

and here's the js: 这是js:

var firstselector = '<select class="firstselectorclass">'+
  '<option value=""></option>'+
  '<option value="1">1</option>'+
  '<option value="2">2</option>'+
  '<option value="3">3</option>'+
  '<option value="4">4</option>'+
  '</select>';

var secondselector =  '<select class="secondselectorclass">'+
  '<option value=""></option>'+
  '<option value="apple">Apple</option>'+
  '<option value="lemon">Lemon</option>'+
  '<option value="orange">Orange</option>'+
  '<option value="banana">Banana</option>'+
  '</select>';

var completerow = '<div class="complrow"><div class="span4">'+ firstselector + '</div><div class="span4">'+ secondselector + '</div><div class="span4"><input type="number" min="0" id="actqty" class="actqtyclass" placeholder="0" style="max-width:50px;"></div></div>';

var result = [{"qty":"1","fruit":"apple","price":"19.00"},
              {"qty":"1","fruit":"lemon","price":"29.00"},
              {"qty":"1","fruit":"orange","price":"39.00"},
              {"qty":"1","fruit":"banana","price":"49.00"},
              {"qty":"2","fruit":"apple","price":"20.00"},
              {"qty":"2","fruit":"lemon","price":"30.00"},
              {"qty":"2","fruit":"orange","price":"40.00"},
              {"qty":"2","fruit":"banana","price":"50.00"},              
              {"qty":"3","fruit":"apple","price":"21.00"},
              {"qty":"3","fruit":"lemon","price":"31.00"},
              {"qty":"3","fruit":"orange","price":"41.00"},
              {"qty":"3","fruit":"banana","price":"51.00"},
              {"qty":"4","fruit":"apple","price":"22.00"},
              {"qty":"4","fruit":"lemon","price":"32.00"},
              {"qty":"4","fruit":"orange","price":"42.00"},
              {"qty":"4","fruit":"banana","price":"52.00"}
             ];

function clearResults()
{
    $('#try').html('');
}

function addAnotherRow(){
     var lastRow = $(".complrow:last");
     $(lastRow).before(completerow);      
     clearResults();
}

$(document).ready(function() {

    addAnotherRow();
    addAnotherRow();
    addAnotherRow();
    clearResults();

    $("#addrow").click(function(){ 
            addAnotherRow(); 
    });

    $('#thisisit').click(function(){
                clearResults(); 
        var errorFound = false;

        //Loop through rows
        var complrowcombination = new Array();
        var sumofquantity = 0;

        $('.complrow').not(':first').not(':last').each(function (i, row)
        {
          var numberselected = $(row).find('.firstselectorclass').val();
          var fruitselected = $(row).find('.secondselectorclass').val();
          var quantity = $(row).find('.actqtyclass').val();             

          sumofquantity += quantity;     

          var thiscomplrowCombination = new Array();
          thiscomplrowCombination[0] = numberselected;
          thiscomplrowCombination[1] = fruitselected;
          thiscomplrowCombination[2] = quantity;

          //push this each line of array to the overall array
          if(quantity > 0)
          {
             complrowcombination.push(thiscomplrowCombination);
          }

        });       

        //Check Overall Sum
        if(sumofquantity == 0)
        {
          alert("You must enter at least one row with quantity greater than 0!");
          return;
        }

        //If no error, get data
        if(errorFound)
        {
          alert("Error found, cannot continue...");
          return;
        } else
        {
          $('#try').html('no error found up to this point');
        }
    });
});

I'm not sure what the ID select field is referencing in your code. 我不确定您的代码中引用的ID选择字段。 In my solution, I'm just using the quantity field and the fruit name. 在我的解决方案中,我仅使用数量字段和水果名称。 Please let me know if this is not what you were looking for. 如果这不是您想要的,请告诉我。

I've made a separate function called getFruitPrice(quantity, fruitName) that gets the price of a fruit in its quantity from the results array. 我制作了一个名为getFruitPrice(quantity, fruitName)的单独函数,该函数从results数组中获取其数量的水果价格。

getFruitPrice() - Getting the fruit price based on the quantity and name of the fruit getFruitPrice()-根据水果的数量和名称获取水果价格

function getFruitPrice(quantity, fruitName) {
    for (var index in result) {
        var fruit = result[index];

        if (fruit.qty == quantity && fruit.fruit.toLowerCase() == fruitName.toLowerCase()) {
            return parseFloat(fruit.price);
        }
    }

    return null;
}

In the main click function, I'm just keeping a variable that holds the total price of the items. 在主点击功能中,我只是保留了一个变量,该变量保存了商品的总价。 When it loops through all of the select fields, it will add on the price obtained from getFruitPrice() . 当它遍历所有选择字段时,它将添加从getFruitPrice()获得的价格。

getFruitPrice() will return null ; getFruitPrice()将返回null so if you're wanting to set a requirement that the user must enter a quantity greater than 1 this must be done here. 因此,如果您要设置一个要求用户必须输入大于1的数量,则必须在此处完成。

Main Click Event 主点击事件

$('#thisisit').click(function(){
    clearResults(); 

    var totalPrice = 0;

    $('.complrow').not(':first').not(':last').each(function (i, row)
    {
        // var numberselected = $(row).find('.firstselectorclass').val();
        var fruitselected = $(row).find('.secondselectorclass').val();
        var quantity = $(row).find('.actqtyclass').val();   

        if (quantity > 0 && quantity < 5) {
            var fruitPrice = getFruitPrice(quantity, fruitselected);

            if (fruitPrice != null) {
                totalPrice += fruitPrice;
            }
        } else if (fruitselected) {
            alert("One of the items has an invalid quantity!");
        }
    });

    alert(totalPrice);
});

I'm just alerting the total price as an example. 我只是提醒总价格为例。

https://jsfiddle.net/ws01muyL/43/ https://jsfiddle.net/ws01muyL/43/

You just need to use parseInt when you add quantities as under: 您在添加数量时只需使用parseInt,如下所示:

sumofquantity += parseInt(quantity); 

check this 检查这个

https://jsfiddle.net/523xp44u/2/ https://jsfiddle.net/523xp44u/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM