0

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. 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.

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:

<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:

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

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

and here's the 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');
        }
    });
});

2 Answers 2

1

I'm not sure what the ID select field is referencing in your code. 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() - Getting the fruit price based on the quantity and name of the fruit

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() will return 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.

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/

Sign up to request clarification or add additional context in comments.

9 Comments

It crashes if quantity is higher than 5.
@Ozan It doesn't crash? It just ignores it and doesn't add anything to the total. I've updated the fiddle anyway, but OP didn't specify what should happen if an invalid quantity is entered
Yeah sorry you are right it just doesn't update the total. That's what I meant. I didn't understand what was OP's problem either. My solution was filtering the results depending on the fruit but since there are more than one with the same name it didn't make sense. My approach was var price = result.filter(x => x.fruit === fruitselected ).map(x => x.price);so that depending on the fruit you would get the price.
since I don't have a limit on the quantity, I should just remove this part of the code, right? "&& quantity < 5"... BTW, to get the price, you need the value of the two selectors, the first one (ID) and the fruit itself. Let's say the ID stands for market A,B,C,etc. That's why price varies depending on the market. How should I tweak the getFruitPrice function to do this? Thank you!
@Ken There is no "market" in your code though. What is ID referring to in your results array? Should there be multiple arrays for each market? If the quantity is greater than a value specified in the results array, what should happen? Don't forget to click the tick to mark the question as answered
|
0

You just need to use parseInt when you add quantities as under:

sumofquantity += parseInt(quantity); 

check this

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

3 Comments

Your solution returns a NaN.
@Ozan I have updated the fiddle to check the case jsfiddle.net/523xp44u/2
ohh, so that's how you convert the value to an integer.. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.