hypertext styling scripting numbers result

As someone who isn't proficient in JavaScript, this question might have a very simple answer that I'm unaware of.

I am working with a grid consisting of 9 buttons, another grid with 9 radio type inputs, and an additional set of 5 radio type inputs. Each of these elements needs to be used in mathematical calculations to display the total cost on the page based on selected attributes like weight and length.

There are 3 specific areas where I need to see the calculated price displayed. I have the prices listed in an Excel sheet but I'm unsure how to create the function for this purpose. The function should be able to determine the price based on selections like the first button, third radio input, second radio input, their values, and the required math formula.

/* Your CSS styles here */
<!-- Your HTML code here -->

To clarify, I need to show the output of the formula on the orange background grid where I've already placed the 3 € signs.

Answer №1

The fundamental approach entails:

  1. Attach a change event to the radio inputs
  2. Upon changing the input value, compute the price
  3. Display the correct price (or various prices) in each of the 3 elements

Here's a straightforward illustration:

document.querySelectorAll('input[type=radio]').forEach(function(input) {
  //add change event to each input
  input.onchange = function() {
    //calculation for price here, e.g.:
    var price;

    if (this.value == '0-1 kg') {
      price = 1;
    } else {
      price = 2;
    };

    //output price here
    document.querySelectorAll('.tabcosti .white')[0].innerText = price;
    document.querySelectorAll('.tabcosti .white')[1].innerText = price;
    document.querySelectorAll('.tabcosti .white')[2].innerText = price;
  };
})
body {
  font-family: "Open Sans", sans-serif;
}

.flex-col {
...
.btn2 {
  background-color: darkorange;
  color: white;
  border: none;
  text-decoration: none;
  flex-grow: 1;
  margin: 10px;
  height: 30px;
}
<div class="justify evenly flex-row">
 ...
</div>

Answer №2

Apologies for the tardiness, but you can leverage the power of the jQuery change event to capture the value of the radio button that was clicked.

Below is a straightforward example:

document.getElementById('large').addEventListener('change', function() {
  var change = document.getElementById('large');
  var times = document.getElementById('times').value / 100;
  if (change.checked) {
    document.getElementById('calories').innerHTML = parseInt(document.getElementById('calories').innerHTML) * times;
  } else {
    document.getElementById('calories').innerHTML = parseInt(document.getElementById('calories').innerHTML) / times;
  }
});
// -------------------
$('input[name=course1]').mouseup(function(e) {
  console.log("Previously " + $('input[name=course1]:checked').val());
  var prevValue = parseInt($('input[name=course1]:checked').val());
  var newvalue = parseInt(e.currentTarget.value);
  console.log("Now " + newvalue);
  document.getElementById('calories').innerHTML = parseInt(document.getElementById('calories').innerHTML) - prevValue;
  document.getElementById('calories').innerHTML = parseInt(document.getElementById('calories').innerHTML) + newvalue;
  console.log("————————————————————");
});
$('input[name=course2]').mouseup(function(e) {
  console.log("Previously " + $('input[name=course2]:checked').val());
  var prevValue = parseInt($('input[name=course2]:checked').val());
  var newvalue = parseInt(e.currentTarget.value);
  console.log("Now " + newvalue);
  document.getElementById('calories').innerHTML = parseInt(document.getElementById('calories').innerHTML) - prevValue;
  document.getElementById('calories').innerHTML = parseInt(document.getElementById('calories').innerHTML) + newvalue;
  console.log("————————————————————");
});
$('input[name=course3]').mouseup(function(e) {
  console.log("Previously " + $('input[name=course3]:checked').val());
  var prevValue = parseInt($('input[name=course2]:checked').val());
  var newvalue = parseInt(e.currentTarget.value);
  console.log("Now " + newvalue);
  document.getElementById('calories').innerHTML = parseInt(document.getElementById('calories').innerHTML) - prevValue;
  document.getElementById('calories').innerHTML = parseInt(document.getElementById('calories').innerHTML) + newvalue;
  console.log("————————————————————");
});

function validate() {
  var value = parseInt(document.getElementById('times').value);
  if (value < 110 || value > 200 || value == "") {
    console.log('failure');
    document.getElementById('times').focus();
    document.getElementById('times').style.borderBottom = '2px solid #ff0000';
  } else {
    document.getElementById('times').style.borderBottom = '2px solid black';
  }
}
#calories::after {
  content: " calories in this meal";
}
#times:focus, #times {
  outline: none !important;
  border-top: none !important;
  border-left: none !important;
  border-right: none !important;
  border-bottom:2px solid black;
}
#times {
  font-family: standard;
  border-bottom:none;
}
<button onclick="console.clear();">Console covering page? Click this button to get rid of all console messages!</button>
<hr>
<input type="checkbox" id="large" />
<label for="large">Large food (<input type="number" min="110" max="200" value="150" id="times" oninput="validate();" onchange="this.style.borderBottom = 'none';" />) % change! (click number to edit)</label>
<hr>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" checked="checked" name="course1" value="0" id="opt1" />
<label for="opt1">I don't want appetizer</label>
<div></div>
<input type="radio" name="course1" value="200" id="opt2" />
<label for="opt2">Peanuts</label>
<hr>
<input type="radio" checked="checked" name="course2" value="0" id="opt3" />
<label for="opt1">I don't want a main course</label>
<div></div>
<input type="radio" name="course2" value="1000" id="opt4" />
<label for="opt4">Pizza</label>
<div></div>
<input type="radio" name="course2" value="2000" id="opt5" />
<label for="opt5">A Whole Pizza</label>
<hr>
<input type="radio" checked="checked" name="course3" value="0" id="opt6" />
<label for="opt6">I don't want dessert!</label>
<div></div>
<input type="radio" name="course3" value="300" id="opt7" />
<label for="opt7">Brownie</label>
<div></div>
<input type="radio" name="course3" value="500" id="opt8" />
<label for="opt8">Cake</label>
<hr>
<p id="calories">0</p>

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

Utilize Vue.js to Customize Meta Title and Description

Would it be feasible to modify elements higher than the body tag in Vue.Js? The data for these elements is currently sourced from a JSON file linked to an element lower in the DOM hierarchy. I am looking to insert a meta title and description that can be ...

What is the best way to trigger useEffect when the state being used within the effect is expected to change during the course of the effect's

Exploring the following code snippet: const [list, setList] = useState([]); const [curPage, setCurPage] = useState(0); const fetchItem = useCallback(async ()=>{ const data = await callAPI(); // data is an object setList(prev => [...prev, data]) ...

Ensuring the footer stays at the bottom of the page using Tailwindcss and ReactJS

I've read numerous articles and posts about achieving this, but none of the methods seem to be effective for me. My goal is to have the footer stick to the bottom of the page when viewed on mobile devices. It displays correctly on larger screens, but ...

Press the button corresponding to a specific custom data-id using the console

I have a collection of items, each represented by a button with a unique data-id, for example: <button type="button" class="stuff" data-id="123"> I am looking to programmatically click on a specific button using its da ...

What is the process for implementing pagination in vue-tables-2 with a Laravel REST API?

I'm looking to implement pagination on Vue server-table using a Laravel endpoint. How can I achieve this? Below is my component setup: <template> <div> <v-server-table :columns="columns" url="/object/find" :options="option ...

The data from the Subscribe API call is gradually loading within the ngOnInit() function

When using Angular 8, I am experiencing slow data retrieval when making API calls in the ngOnInit() function. The issue arises when trying to pass this data as @Input from one component module to another - it initially comes through as undefined for a minu ...

Having difficulty aligning my navigation menu with HTML and CSS

I'm having difficulty centering this menu. I've experimented with adjusting margins, using the center tag, and inserting a div, but nothing seems to be working. Any assistance would be greatly appreciated. Thanks! Feel free to view the JSFiddle ...

Creating a grid UI in AngularJS using Typescript: utilizing functions as column values

I am working on an AngularJS app that includes the following UI grid: this.resultGrid = { enableRowSelection: true, enableRowHeaderSelection: false, enableHorizontalScrollbar: 0, enableSorting: true, columnDefs: [ { name: &apos ...

Error in Javascript: unable to locate the imported module

When attempting to import the 'CryptographyClient' module from a specified directory, I encountered an issue. Initially successful in typescript, but after compiling the code into javascript, an error was thrown stating that it could not find the ...

AngularJS - Issue with retrieving the most recent entry during $routeChangeStart event

I am utilizing the $routeChangeStart function to redirect authorized users to specific URLs and prevent unauthorized access to special pages. In addition, I have dynamically generated pages that can be accessed via their unique page slugs. To achieve this ...

Are there any CSS styles available for targeting an element with any id?

I need to style h2 tags in HTML documents that have an id attribute, without styling the ones without an id. I want to achieve this using only CSS and not by modifying the HTML structure. Specifically, I want to target these h2 elements with a CSS rule: ...

The inner nested ng-repeat section is not properly binding to the scope variable and appears to be commented out

In my code, there is a nested ng-repeat set up. The 'boards' variable in the scope is an array that contains another array called 'tasks', which also consists of arrays. In the innermost ng-repeat, I am attempting to bind to task.conten ...

When using server-side rendering in React with AJAX, an error may occur if trying to call setState

In order to display data to the user, I rely on the response from the AJAX request as I store all necessary information in the database. My component GenericPage.jsx: export default class GenericPage extends React.Component { componentWillMount() { ...

The sidebar navigation is not appearing on Safari and IOS devices

I am facing an issue with my fixed position navbar and sidebar menu buttons on mobile, specifically on IOS and Safari. When clicking on the cart or account buttons, the sidebar menu does not show up. It seems to be a compatibility issue, and I am looking f ...

Adjusting the size or compressing images during the upload process to Firebase

I have a Google Cloud function that successfully uploads images, but I want to add functionality to compress the image in order to prevent excessive charges for uploading large files. Any suggestions on how to achieve this would be highly appreciated! He ...

Decoding the Blueprint of Easel in JavaScript

Recently, I came across a fantastic API that promises to simplify working with CANVAS by allowing easy selection and modification of individual elements within the canvas. This API is known as EaselJS, and you can find the documentation here. While I foun ...

What is the most effective approach for addressing errors in both the server and client sides while utilizing nodejs and express?

Seeking the most effective approach for handling errors in a response - request scenario. Here is an example of a route that receives a request: app.get('/getInfo', function (req, res, next) { let obj = {} try { obj = { ...

Ways to prevent position fixed from overlapping with footer?

Is there a way to prevent a floating box from overlapping the footer div and stop it at a certain point within the main div? window.onload = function () { var scrolledElement = document.getElementById('scrolling_box'); var top = scrolled ...

Is there a way to obtain the ultimate outcome from an array of asynchronous functions efficiently?

get-video-duration is a useful npm module designed to fetch the duration of a video. const { getVideoDurationInSeconds } = require('get-video-duration') // Accessing the duration from a local path... getVideoDurationInSeconds('video.mov&ap ...

Use PHP to dynamically assign a class to each <option> element within a loop

How do I go about adding a CSS class to every option within my code? Here is the PHP code provided, and you can refer to the screenshot below for where the class property should be placed - what adjustments should be made in order to include a class in eac ...