Creating a user-friendly product customization tool using fundamental JS, HTML, and CSS techniques

Can anyone provide me with some tips on the best practices for structuring JavaScript code? I am working on creating a tool for a smoothie shop owner where customers can select ingredients, and we need to calculate the total amount of sugar and vitamins. However, I am struggling to figure out how to combine all these parameters in JavaScript.

EarlyBirdSmoothie: Apple - Vitamin A = UI200, Vitamin C = UI300, Sugar = 200mg

Pear: Orange C = UI3000, Vitamin A = UI1000, Sugar = 250mg

Orange: Vitamin C = UI3000, Sugar = 250mg

Each fruit has a unique combination of Vitamins and Sugar, e.g., Orange = Vitamin C 3000UI + 250mg Sugar

Product builder with an overview: When a staff member orders a smoothie with Apple, Pear & Orange, we need to calculate the total amount of Vitamins UI and Sugar MG, along with individual Vitamin and Sugar content of each ingredient.

Editing option for created products: Ideally, we should be able to create a list of bestselling soups that can be reused, and allow for adding or removing ingredients from the soup.

What is the best technique to achieve this and how can it be done?

I have made a rough estimation of how I would approach this to get started:

Here is my current mockup:

// Custom function
function calculateTip() {

// Store the data of inputs
var vitaminTypes = document.getElementById("vitaminTypes").value;
var vitaminAmount = document.getElementById("vitaminAmount").value;
var sugarAmount = document.getElementById("sugarAmount").value;
var ingredientTypes = document.getElementById("ingredientTypes").value;
    
// Quick validation
if(fruitAmount === "" || serviceQuality == 0) {
window.alert("Please enter some values to get this up and running!");
return; // this will prevent the function from continuing
}
    
// Check to see if this input is empty or less than or equal to 1
if(numFruits === "" || numFruits <= 1) {
numPeople = 1;
        
document.getElementById("each").style.display = "none";        
} else {
        
document.getElementById("each").style.display = "block";        
}
    
// Do some math!
var total = (vitaminType * vitaminAmount) ;
total = Math.round(total * 100);
total = total.toFixed(2);
    
    
// Display the content!
document.getElementById("totalAmount").style.display = "block";
document.getElementById("amount").innerHTML = total;
}

// Hide the content info amount on load
document.getElementById("totalAmount").style.display = "none";
document.getElementById("each").style.display = "none";

// Clicking the button calls our custom function
document.getElementById("calculate").onclick = function() { calculateAmount(); }

Answer №1

To be transparent, I must admit that I didn't grasp all the intricacies of your code, but I do have a few suggestions to offer:

  • Consider swapping out == with ===, such as in this instance: serviceQuality === 0. JavaScript tends to coerce values when using == for comparison: '' == 0 // true
  • It seems like the variable numPeople is not initialized within your function. This lack of initialization can lead to impurities in the function, potentially causing issues later as your code base expands. Attempt incorporating it as an argument.
  • You seem to handle a significant amount of styling within your JavaScript code, which could potentially be achieved (and possibly improved) through CSS and pseudo classes like :valid. Utilizing CSS not only simplifies your code but also enhances its robustness. Performing style manipulations as you currently are can result in numerous repaints. If transitioning to CSS, I recommend checking out this resource: here!
  • While I'm uncertain about this point, using addEventListener('click', ... ) might be preferable over directly attaching the onclick method.
  • Alternatively, you could explore utilizing frameworks like React, Angular2, or Ember, as they may streamline the task at hand.

I hope these suggestions prove helpful! \[.__.]/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Depths with a Javascript Canvas Deep Zoom Library

I am faced with the task of creating a detailed zoom mosaic using an HTML5 Canvas Element, consisting of thousands of roughly 512x512 images. However, I am striving to minimize reinventing the wheel in the process. Instead of merging numerous large images ...

Having trouble retrieving information from ajax to php

I'm struggling to understand why this code is not functioning as expected: idcurso= res[0]; idusuario= res[1]; semana= res[2]; fecha=res[3]; asistencia= true; $.ajax({ type: "POST", url: '/test/7/tomarasistencia.php', data: { ...

The variable that was posted is not being successfully transferred within the query

There seems to be an issue with retrieving data from the ajax call in ajaxcall.php and assigning it to $place = $_POST['place']; in listplace.php. Despite this problem, the code runs smoothly otherwise. I've tried numerous times to get the ...

What is the best way to load data into a specific product popup in Magento?

I'm looking to display product details in a pop-up when the product name is clicked on the product page. Below is the code I am currently using: <?php if (count($data['product']) > 0) { forea ...

Enhancing specific child value in Firebase Database using JavaScript: Exploring Firebase Realtime capabilities

I have a database structure where I need to update the value of isseen to true when the sender is equal to "5". Here's an example of my database structure: Chats -LvuhnORi1ugp8U2Ajdq isseen: "false" message: "hi" receiver: "OX0pReHXfXUTq1XnOnTSX7moiG ...

A program designed to automatically upload images

I'm currently working on a website project that showcases various events. Here is a sneak peek: https://i.sstatic.net/W3a4U.jpg While I can customize the HTML and CSS to add more events similar to the one shown above, it becomes tedious having to ma ...

Sharing node_modules via Npm and ensuring the package.json is correctly mapped

I have a dilemma with two projects, one serving as a server and the other as a client. They share very similar dependencies, making it tedious to set up shared dependencies without manual file editing or installing everything twice. The issue is exacerbate ...

Does adding the Angular bootstrap script at the end of the body tag impact webpage speed more than using ng-app on the body tag?

In the past, we had placed ng-app on the body tag which led to problems with dependency injection when multiple modules were being used on the same webpage. This required module creators to be aware of the existing app and inject their app into it. We are ...

What is the best method for transforming a nested object into an array of objects?

This object contains nested data var arr = [{ "children": [{ "children": [{ "children": [], "Id": 1, "Name": "A", "Image": "http://imgUrl" }], "Id": 2 "Name": "B", ...

Using Various Buttons in a Bootstrap Form

I have implemented Bootstrap to create a form. The form structure is as follows: <form action="default_results.php" method="post" class="calculator" name="frmCalculator"> At the beginning of my code, I used the above form code. At the end of the pa ...

What is the reason for `change()` not being defined in the constructor? Is it supposed to be accessed through the `__proto__` link in `

Why is the change() method not defined in the constructor? Shouldn't it be accessed through the proto link in the p.proto? // The first change() is not defined, why? class Person { constructor() { console.log(this) console.log(this.__prot ...

Issue with manipulating currency conversion data

Currently, I am embarking on a project to develop a currency conversion application resembling the one found on Google's platform. The main hurdle I am facing lies in restructuring the data obtained from fixer.io to achieve a similar conversion method ...

Utilizing an EJS template within an express.js application to extract and assign data to a variable

Is there a way to transfer data from my node.js (express) app directly to a variable within the <script> tag on the page? On the server-side, I have the following code: let tmp = JSON.stringify(await f(i)); console.log(tmp); //correct data [{"i ...

Is there a benefit to using the Angular LocalStorageModule alongside angular-cache?

To configure the angular-cache, follow this setup: app.service('myService', function ($angularCacheFactory) { // This cache will synchronize with localStorage if available. Upon each app load, it will attempt to retrieve any previously save ...

Is there a way to remove a dynamically rendered component from a list?

Whenever I click a button, the same component is dynamically rendered on top of the list. But now, I need to implement a feature where users can delete any component from the list by clicking a cancel button associated with each component. Here's my ...

Interactive image popups with JavaScript

Seeking assistance in generating a popup when selecting an area on an image map using Javascript. As a novice in JS, I have successfully implemented popups for buttons before but encountered issues with this code within the image map - the popup appears br ...

unable to record the input value in jquery

Snippet for HTML code: <div id="Background"> <input id="search-Bar" type="text"> <button id="SearchButton">Search</button> </div> var name = $("#search-Bar").val(); $("#SearchButton").on("click", function() { co ...

Using JavaScript to dynamically calculate the sum of selected column values in Angular Datatables

I have a table set up where, if a checkbox is checked, the amounts are automatically summed and displayed at the top. However, I am encountering issues with the code below as it is not providing the exact sum values. Can anyone suggest a solution to this p ...

Dynamically adding script tags to inject HTML files into a webpage

I have a primary web page, index.htm, that dynamically inserts html files. Everything is functioning correctly. However, what should I do if I add component.htm twice to the same page? When the component html is added for the second time, the $('.foo ...

retrieve a string from a given array

I need to retrieve a string from an array in vue and display it on the screen. Here is the method I created for this purpose: displayFixturesName() { const result = this.selectedFixture.toString(); document.getElementById(& ...