how to display a generated select option based on its row in a dynamic select box

Viewed 743

I have some problem with displaying a select option after i add a new one in dynamic select box. So the one i have here display the result of first row select box. While i change the qty and click order it will change the price result but after changing the option it will display result under the first one. For the result i need to change this code so when i click order button the result will display like this: if i have 3 rows of select boxes, the result will display each of it into 3 rows. Any help would be appreciated!

example

This is the example when i click order the first select box row, it display name=price*qty (this is the result i need for each select box) img1

This is the example when i change the first select box row option, it display a new result under the first result instead changing it img2

code

$(document).ready(function () {
        var selectMenu = {};
        $('.order').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, "")
            //the result in the first row change price based on qty, but when option is changed the result display under the first one

            $('.result').html(result);

Here is the link for full code: jsbin

2 Answers

You can use each loop because you might be having mutliple select-boxes for each row . Then , get price & quantity from each row and add save same inside JSON Object . Now, to show them use .each loop again and append new rows inside some divs.

I have created JSON structure like this :

{
  //here 0 is first row  
  "0": {
      "total": 0, //this is total for first row
      "itemname": "Fried Rice" //this is price for first row
    } 
  //same for other rows as well only changing  1 ,2..etc
}

Demo Code :

$(document).ready(function() {
  $('.order').click(function() {
    var selectMenu = {};
    //loop through type select
    $("select.type").each(function(i) {
      selectMenu[i] = {} //create array
      //get label value
      var text = $(this).find("option:selected").attr('label');
      //get price
      var price = Number($(this).find("option:selected").data('price'));
      //get qty
      var qty = Number($(this).closest(".row").find(".qty").val())
      //push same in array
      selectMenu[i] = {
        "total": price * qty,
        "itemname": text
      }
    })

    $('.result tbody').html(""); //clear tbody
    $.each(selectMenu, function(index, data) {
      //add tr inside tbody
      $('.result tbody').append("<tr class='orders'><td>" + data.itemname + '</td><td>' + data.total + "</td></tr>");
    })
  });

});
.orders {
  color: green;
  font-weight: bold;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/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>
<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-3">
        <button type="button" class="btn btn-primary btn-lg addRow">Add</button>
      </div>
      <div class="col-md-3">
        <!--added class cat -->
        <select class="form-select form-select-lg mb-3 cat" id="category_select" onChange='handleChange(this)'>
          <option value="Food">Food</option>
          <option value="Drink">Drink</option>
        </select>
      </div>
      <br>
      <div class="col-md-3">
        <!--added class type -->
        <select class="form-select form-select-lg mb-3 type" id="type_select">
          <option value="1" label="Fried Rice" data-price="10000"></option>
          <option value="2" label="Fried Noodle" data-price="9000"></option>
          <option value="3" label="Pancake" data-price="8500"></option>
          <option value="4" label="French Fries" data-price="7500"></option>
        </select>
      </div>
      <div class="col-md-3">
        <input type="number" class="form-control form-control-lg mb-3 qty" id="num" placeholder="Qty" min="0">
      </div>
    </div>
    <div class="row">
      <div class="col-md-3">
        <button type="button" class="btn btn-danger btn-lg ">Delete</button>
      </div>
      <div class="col-md-3">
        <select class="form-select form-select-lg mb-3 cat" onChange='handleChange(this)'>
          <option value="Food">Food</option>
          <option value="Drink">Drink</option>
        </select>
      </div>
      <br>
      <div class="col-md-3">
        <select class="form-select form-select-lg mb-3 type">
          <option value="1" label="Fried Rice" data-price="10000"></option>
          <option value="2" label="Fried Noodle" data-price="9000"></option>
          <option value="3" label="Pancake" data-price="8500"></option>
          <option value="4" label="French Fries" data-price="7500"></option>
        </select>
      </div>
      <div class="col-md-3">
        <input type="number" class="form-control form-control-lg mb-3 qty" id="num" placeholder="Qty" min="0">
      </div>
    </div>
  </div>
</div>
<br>
<button type="button" class="btn btn-secondary order">Order</button>
<br>
<br>
<div class="result text-center">
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>Item name </th>
        <th>Price</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

I've done a bit of refactoring, because you were using same ids on multiple elements, so I changed them to classes. Full code: jsbin

        $(document).ready(function () {
        var selectMenu = {};
        $('.order').click(function () {
             selectMenu = {};
            $('.menu-position').each(function (i) {
                var category = $(this).find('.category-select').val()
                var $selectedItem = $(this).find('.type-select :selected')
                var name = $selectedItem.attr('label')
                var price = $selectedItem.data('price')
                var qty = +$(this).find('.qty').val()
                var total = price * qty
                
                selectMenu[name] = total
            })
            
            var result = JSON.stringify(selectMenu).replace(/,/g, '<br>').replace(/\{|\}|"/g, "")
            $('.result').html(result);
        });

    });

Your order function had two errors:

  1. You were processing only the first menu row.
  2. You you were using the same "selectMenu" object instead of creating a new one.
Related