skip to Main Content

I’m trying to build a cart function for the existing Food ordering system.

There, the user can view the product price in

<div class="product__price m-t-5">
  <span class="product__price product__price--large">[email protected](model => model.ProductPrice)</span>
</div>

section.

If the selected product is customizable, I show the extra items in the view with Checkbox.

So what I want to know is, if the customer selects any extra items, the extra item price should be added to the main price.

Also, if a customer is unchecked, then it should subtract from the main amount.

Want to know how to do this using Javascript?

This is the HTML code.

  <div class="col-md-7">
   <div class="product-details-box m-b-60">
     <h4 class="font--regular m-b-20">@Html.DisplayFor(model => model.ProductName)</h4>
     <div class="product__price m-t-5">
       <span class="product__price product__price--large">[email protected](model => model.ProductPrice)</span>
     </div>
     <div class="product-var p-tb-30">
       <div class="product-quantity product-var__item d-flex align-items-center">
         <span class="product-var__text">Quantity: </span>
         <form class="quantity-scale m-l-20">
           <div class="value-button" id="decrease" onclick="decreaseValue()">-</div>
           <input type="number" id="number" name="number" value="1" />
           <div class="value-button" id="increase" onclick="increaseValue()">+</div>
         </form>
       </div>
       <div>
         <h4 class="font--regular m-b-20">Add Some Extra</h4> 
         @if (Model.CustomizableFoods.Count!=0) 
         { 
         foreach (var item in Model.CustomizableFoods)
         { 
         <div class="row">
           <ul class="list">
             <li class="list__item">
               <label class="label--checkbox">
                 <input type="checkbox" class="checkbox"> &nbsp; &nbsp; &nbsp; @item.ExtraItem - @item.Extra_Item_Price </label>
             </li>
           </ul>
         </div>
            } 
        }
       </div>
       <div class="product-var__item">
         <input class="btn btn--long btn--radius-tiny btn--green btn--green-hover-black btn--uppercase btn--weight m-r-20" type="submit" value="Add to cart" />
         <a href="wishlist.html" class="btn btn--round btn--round-size-small btn--green btn--green-hover-black">
           <i class="fas fa-heart"></i>
         </a>
       </div>
       <div class="product-var__item">
         <span class="product-var__text">Guaranteed safe checkout </span>
       </div>
       <div class="product-var__item d-flex align-items-center">
         <span class="product-var__text">Share: </span>
         <ul class="product-social m-l-20">
           <li>
             <a href="#">
               <i class="fab fa-facebook-f"></i>
             </a>
           </li>
           <li>
             <a href="#">
               <i class="fab fa-twitter"></i>
             </a>
           </li>
           <li>
             <a href="#">
               <i class="fab fa-pinterest-p"></i>
             </a>
           </li>
         </ul>
       </div>
     </div>
   </div>
 </div>

This is a sample of the view,

enter image description here

I did this,

In the view

 @if (Model.CustomizableFoods.Count!=0) 
 { 
    foreach (var item in Model.CustomizableFoods) 
     {  
     <div class="row">
        <ul class="list">
            <li class="list__item">
                <label class="label--checkbox">
                    <input type="checkbox" class="checkbox" onclick="thisChecked()" value="@item.Extra_Item_Price"> &nbsp; &nbsp; &nbsp; @item.ExtraItem - @item.Extra_Item_Price </label>
            </li>
        </ul>
      </div> 
    } 
 }
```

in the script

```
< script >
  function thisChecked() {

    var sList = "";
    $('input[type=checkbox]').each(function () {
      sList += "(" + $(this).val() + "-" + (this.checked ? "checked" : "not checked") + ")";
    });

    alert(sList);

  } <
  /script>

```
as a result the alert shows

```
(100.00-checked)(450.00-not checked)
```

So any way of getting only the selected value to one variable and checked or not checked to another?

2

Answers


  1. You can use data-attribute which will have the original amount of the product and using that you can add or subtract extra items inside thisChecked function

    Also, make sure the attribute value should be updated always when you call your decreaseValue / increaseValue functions .

    Demo Code :

    function thisChecked(el) {
    
      var closest_price_element = $(el).closest('.product-details-box').find('span.product__price');
      var amount = parseFloat(closest_price_element.data('original')) ?? 0; //getting attr value ..
      $('.product-var input[type=checkbox]:checked').each(function() {
        amount += parseFloat($(this).val()); //loop and addiing items amt
      });
    
      closest_price_element.text('$' + amount); //change value of price
    
    }
    
    //***the data-attr should be updated..always..not sure about decreaseValue / increaseValue fn there also you need to update the data attr value so that it always take original amount .!!
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="col-md-7">
      <div class="product-details-box m-b-60">
        <h4 class="font--regular m-b-20">PIZZA</h4>
        <div class="product__price m-t-5">
          <!--here added orginal price in data attr data-original= '@model.ProductPrice' -->
          <span class="product__price product__price--large" data-original='1200'>$1200</span>
        </div>
        <div class="product-var p-tb-30">
          <div class="product-quantity product-var__item d-flex align-items-center">
            <span class="product-var__text">Quantity: </span>
            <form class="quantity-scale m-l-20">
              <div class="value-button" id="decrease" onclick="decreaseValue()">-</div>
              <input type="number" id="number" name="number" value="1" />
              <div class="value-button" id="increase" onclick="increaseValue()">+</div>
            </form>
          </div>
          <div>
            <h4 class="font--regular m-b-20">Add Some Extra</h4>
    
            <div class="row">
              <ul class="list">
                <li class="list__item">
                  <label class="label--checkbox">
                  <!--pass current element reference-->
                     <input type="checkbox" class="checkbox" onclick="thisChecked(this)" value="10"> &nbsp; &nbsp; &nbsp; Cheese - 10  </label>
                </li>
              </ul>
            </div>
            <div class="row">
              <ul class="list">
                <li class="list__item">
                  <label class="label--checkbox">
                     <input type="checkbox" class="checkbox" onclick="thisChecked(this)" value="100"> &nbsp; &nbsp; &nbsp; XYZ - 100 </label>
                </li>
              </ul>
            </div>
    
          </div>
    
        </div>
      </div>
    </div>
    Login or Signup to reply.
  2. Here is the solution of your question :

    1. Add a ‘data-price’ attribute in your html code:
        <span class="product__price product__price--large" data-price="1800"
                    >[email protected](model => model.ProductPrice)</span
                  >
    
    1. Update the html code to render list of extra items:
        @if (Model.CustomizableFoods.Count!=0) 
         { 
            foreach (var item in Model.CustomizableFoods) 
             {  
             <div class="row">
                <ul class="list extra_items">
                    <li class="list__item">
                        <label class="label--checkbox">
                            <input type="checkbox" class="checkbox extra_item" value="@item.Extra_Item_Price"> &nbsp; &nbsp; &nbsp; @item.ExtraItem - @item.Extra_Item_Price </label>
                    </li>
                </ul>
              </div> 
            } 
         }
    
    1. And finally update the javascript code :
        < script >
            // Array of selected items / Items to calculate the price
          let all_items = [];
        
        //   Function to update the price in the UI
          const updatePrice = (JQueryThis) => {
            // Traversing the current card to get price of the cuurent item (not extra_item)
            const priceTag = JQueryThis.parentsUntil(".product-details-box")
              .parent()
              .children("div.product__price")
              .children("span.product__price");
        
            //   Initial price
            let totalPrice = 0;
            for (let item of all_items) {
              if (item.selected) {
                totalPrice += item.price;
              }
            }
        
            priceTag.text(totalPrice);
          };
        
          // This code will run when a user selects or deselects an extra item.
          $(".extra_item").change(function () {
        
            // Traverse HTML Tag in which the total price is rendered
            // I have used traversal to find the price tag of corresponding food product 
            In case if there is more than one food products available.
            const priceTag = $(this)
              .parentsUntil(".product-details-box")
              .parent()
              .children("div.product__price")
              .children("span.product__price");
        
            /*   A JavaScript array of objects that contains details of an extra item. for ex. {
                name: <extra_item__name>,
                price: <extra_item__price>,
                selected: <whether the user selected the extra item or not. true if selected and false if not so.>,
            }
            */
            const extra_items = Array.from(
              $(this).parents(".extra_items").children() // This will return <li> tag
            ).map((item) => {
              let [name, price] = item.innerText.split("-"); // Split the text from '-'
              return {
                name,
                price: Number(price),
                selected: item.querySelector("input[type=checkbox]").checked,
              };
            });
        
            // Update 'all_items' array with the main price and extra items
            all_items = [
              {
                price: Number(priceTag.attr("data-price")),
                selected: true,
              },
              ...extra_items,
            ];
        
            // Update the price in UI
            updatePrice($(this));
          });
        </script>
    

    Warning : Make sure to update the price in backend for security reasons.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search