jQuery addClass example

Change class name on click in jQuery

by Dmitri Ganenco

HTML

<select id='categories'></select>

<table id='availableFoodByCategory' style='display:none;'>
  <thead>
    <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Quantity</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>

JavaScript

const hardCodedFood = [

  {
    "id": "1",
    "Name": "Coke 500ml",
    "Price": "80",
    "Quantity": "50",
    "Category": "Beverages"
  },

  {
    "id": "2",
    "Name": "Cake",
    "Price": "150",
    "Quantity": "40",
    "Category": "Appetizer"
  },

  {
    "id": "3",
    "Name": "Beef Ribs",
    "Price": "100",
    "Quantity": "50",
    "Category": "Side Items"
  },

  {
    "id": "4",
    "Name": "Cabbage Salad",
    "Price": "50",
    "Quantity": "30",
    "Category": "Salads"
  },

  {
    "id": "5",
    "Name": "Cake",
    "Price": "150",
    "Quantity": "30",
    "Category": "Appetizer"
  },

  {
    "id": "6",
    "Name": "Beef Ribs",
    "Price": "100",
    "Quantity": "30",
    "Category": "Side Items"
  }
];

const $categories = $('#categories');
const $availableFoodByCategory = $('#availableFoodByCategory');

hardCodedFood.forEach(el => {
  let $option = $('<option/>', {
    value: el.Category,
    text: el.Category
  });

  $option.appendTo($categories)
});

$categories.on('change', function() {
  $availableFoodByCategory.empty();
  hardCodedFood
    .filter(el => el.Category === $(this).val())
    .forEach(el => {
      let $row = $('<tr/>');
			$('<td/>', {text: el.id}).appendTo($row);
			$('<td/>', {text: el.Name}).appendTo($row);
			$('<td/>', {text: el.Price}).appendTo($row);
			$('<td/>', {text: el.Quantity}).appendTo($row);
			
			$row.appendTo(availableFoodByCategory);
    });
		
		$availableFoodByCategory.show();
});