Dave Christion
Dave Christion

Reputation: 91

how to count the price of select option based on its quantity with javascript

I have created a quantity input here but I can't find a way how to count the price data to match how much quantity I picked. For the result, it should be like the first one here but instead of count the price on how many click buttons, into how many quantities I want to order. Any tips on what method I can use?

Here is the code:

var data = {
            Food: [
                {
                    id: 1,
                    name: 'Fried Rice',
                    price: 10000
                },
                {
                    id: 2,
                    name: 'Fried Noodle',
                    price: 9000
                },
                {
                    id: 3,
                    name: 'Pancake',
                    price: 8500
                },
                {
                    id: 4,
                    name: 'French Fries',
                    price: 7500
                }
            ],
            Drink: [
                {
                    id: 1,
                    name: 'Cola',
                    price: 4600
                },
                {
                    id: 2,
                    name: 'Orange Juice',
                    price: 5400
                },
                {
                    id: 3,
                    name: 'Mineral Water',
                    price: 3500
                },
                {
                    id: 4,
                    name: 'Coffee',
                    price: 5800
                }
            ]
        }

        function handleChange() {
            var x = document.getElementById("category_select").value;

            var dataOptions = data[x]
            var dataSelect = document.getElementById('type_select')
            dataSelect.innerHTML = ''

            dataOptions.forEach(function (option) {
                var optionEle = document.createElement('option')
                optionEle.value = option.id
                optionEle.label = option.name
                optionEle.setAttribute('data-price', option.price)

                dataSelect.appendChild(optionEle)
            })

        }
        handleChange()

        $(document).ready(function () {
            var selectMenu = {};
            $("button").click(function () {
                var itemName = $("#type_select option:selected").attr('label');
                var price = Number($("#type_select option:selected").data('price'));
                if (selectMenu.hasOwnProperty(itemName)) {
                    selectMenu[itemName] += price;
                } else {
                    selectMenu[itemName] = price;
                }
                var result =JSON.stringify(selectMenu).replace(/,/g,'<br>').replace(/\{|\}|"/g,"")

                $(".result").html(result);
            });
        });
button {
            width: 50%;
            margin-left: 25%;
            margin-right: 25%;
        }
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <link type="text/css" rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

    <style>
        button {
            width: 50%;
            margin-left: 25%;
            margin-right: 25%;
        }
    </style>
    <title>Menu</title>
</head>

<body>
    <div class="container">
        <div class="container-fluid text-center">
            <h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <select class="form-select form-select-lg mb-3" id="category_select" onChange='handleChange()'>
                        <option value="Food">Food</option>
                        <option value="Drink">Drink</option>
                    </select>
                </div>
                <br>
                <div class="col-md-4">
                    <select class="form-select form-select-lg mb-3" id="type_select"></select>
                </div>
                <div class="col-md-4">
                    <input type="number" class="form-control form-control-lg mb-3" id="num">
                </div>
            </div>
        </div>
    </div>
    <br>
    <button type="submit" class="btn btn-secondary">Order</button>
    <br>
    <br>
    <div class="result text-center"></div>

Upvotes: 1

Views: 799

Answers (3)

Frenchy
Frenchy

Reputation: 17037

Ok, I have modified your program to add and recalculate following the number of items. I have a test to avoid negative number...but you should avoid the input of id num to be negative.

var data = {
            Food: [
                {
                    id: 1,
                    name: 'Fried Rice',
                    price: 10000
                },
                {
                    id: 2,
                    name: 'Fried Noodle',
                    price: 9000
                },
                {
                    id: 3,
                    name: 'Pancake',
                    price: 8500
                },
                {
                    id: 4,
                    name: 'French Fries',
                    price: 7500
                }
            ],
            Drink: [
                {
                    id: 1,
                    name: 'Cola',
                    price: 4600
                },
                {
                    id: 2,
                    name: 'Orange Juice',
                    price: 5400
                },
                {
                    id: 3,
                    name: 'Mineral Water',
                    price: 3500
                },
                {
                    id: 4,
                    name: 'Coffee',
                    price: 5800
                }
            ]
        }

        function handleChange() {
            var x = document.getElementById("category_select").value;

            var dataOptions = data[x]
            var dataSelect = document.getElementById('type_select')
            dataSelect.innerHTML = ''

            dataOptions.forEach(function (option) {
                var optionEle = document.createElement('option')
                optionEle.value = option.id
                optionEle.label = option.name
                optionEle.setAttribute('data-price', option.price)

                dataSelect.appendChild(optionEle)
            })

        }
        handleChange()

        $(document).ready(function () {
            var selectMenu = {};
            $("button").click(function () {
                var itemName = $("#type_select option:selected").attr('label');
                var price = Number($("#type_select option:selected").data('price'));
                if( Number($("#num").val())<=0)return;

                if (selectMenu.hasOwnProperty(itemName)) {
                    selectMenu[itemName] = price * Number($("#num").val());
                } else {
                    selectMenu[itemName] = price * Number($("#num").val());
                    selectMenu["Nbr"] = Number($("#num").val());
                }
                var result =JSON.stringify(selectMenu).replace(/,/g,'<br>').replace(/\{|\}|"/g,"")

                $(".result").html(result);
            });
        });
button {
            width: 50%;
            margin-left: 25%;
            margin-right: 25%;
        }
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <link type="text/css" rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

    <style>
        button {
            width: 50%;
            margin-left: 25%;
            margin-right: 25%;
        }
    </style>
    <title>Menu</title>
</head>

<body>
    <div class="container">
        <div class="container-fluid text-center">
            <h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <select class="form-select form-select-lg mb-3" id="category_select" onChange='handleChange()'>
                        <option value="Food">Food</option>
                        <option value="Drink">Drink</option>
                    </select>
                </div>
                <br>
                <div class="col-md-4">
                    <select class="form-select form-select-lg mb-3" id="type_select"></select>
                </div>
                <div class="col-md-4">
                    <input type="number" class="form-control form-control-lg mb-3" id="num">
                </div>
            </div>
        </div>
    </div>
    <br>
    <button type="submit" class="btn btn-secondary">Order</button>
    <br>
    <br>
    <div class="result text-center"></div>

Upvotes: 1

Aalexander
Aalexander

Reputation: 5004

Read out the input field where you specify the amount

var amount = Number($("#num").val());

Then multiply it by your price

selectMenu[itemName] = (price*amount);

var data = {
  Food: [{
      id: 1,
      name: 'Fried Rice',
      price: 10000
    },
    {
      id: 2,
      name: 'Fried Noodle',
      price: 9000
    },
    {
      id: 3,
      name: 'Pancake',
      price: 8500
    },
    {
      id: 4,
      name: 'French Fries',
      price: 7500
    }
  ],
  Drink: [{
      id: 1,
      name: 'Cola',
      price: 4600
    },
    {
      id: 2,
      name: 'Orange Juice',
      price: 5400
    },
    {
      id: 3,
      name: 'Mineral Water',
      price: 3500
    },
    {
      id: 4,
      name: 'Coffee',
      price: 5800
    }
  ]
}

function handleChange() {
  var x = document.getElementById("category_select").value;

  var dataOptions = data[x]
  var dataSelect = document.getElementById('type_select')
  dataSelect.innerHTML = ''

  dataOptions.forEach(function(option) {
    var optionEle = document.createElement('option')
    optionEle.value = option.id
    optionEle.label = option.name
    optionEle.setAttribute('data-price', option.price)

    dataSelect.appendChild(optionEle)
  })

}
handleChange()

$(document).ready(function() {
  var selectMenu = {};
  $("button").click(function() {
    var itemName = $("#type_select option:selected").attr('label');
    var amount = Number($("#num").val());
    var price = Number($("#type_select option:selected").data('price'));
    if (selectMenu.hasOwnProperty(itemName)) {
      selectMenu[itemName] += (price*amount);
    } else {
      selectMenu[itemName] = (price*amount);
    }
    var result = JSON.stringify(selectMenu).replace(/,/g, '<br>').replace(/\{|\}|"/g, "")

    $(".result").html(result);
  });
});
button {
  width: 50%;
  margin-left: 25%;
  margin-right: 25%;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

  <style>
    button {
      width: 50%;
      margin-left: 25%;
      margin-right: 25%;
    }
  </style>
  <title>Menu</title>
</head>

<body>
  <div class="container">
    <div class="container-fluid text-center">
      <h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
      <br>
      <div class="row">
        <div class="col-md-4">
          <select class="form-select form-select-lg mb-3" id="category_select" onChange='handleChange()'>
            <option value="Food">Food</option>
            <option value="Drink">Drink</option>
          </select>
        </div>
        <br>
        <div class="col-md-4">
          <select class="form-select form-select-lg mb-3" id="type_select"></select>
        </div>
        <div class="col-md-4">
          <input type="number" class="form-control form-control-lg mb-3" id="num">
        </div>
      </div>
    </div>
  </div>
  <br>
  <button type="submit" class="btn btn-secondary">Order</button>
  <br>
  <br>
  <div class="result text-center"></div>

Upvotes: 1

user12251399
user12251399

Reputation:

If I understood you correctly

First you have to get count of products you want to buy

Then just simply multiply and you will have the total

$("button").click(function() {
  var itemName = $("#type_select option:selected").attr('label');
  var price = Number($("#type_select option:selected").data('price'));
  var count = Number($("#num").val());
  var total = price * count;
  selectMenu[itemName] = total
  var result = JSON.stringify(selectMenu).replace(/,/g, '<br>').replace(/\{|\}|"/g, "")

  $(".result").html(result);
});

Upvotes: 1

Related Questions