Calculating the sum of different functions

I am having an issue with my total_price function. I have tried to implement it in the totalPrice paragraph that I previously created, but it does not display.

function calcAdult()
{
    var ticketPrice = 12;
    var amount = document.getElementById('SAinput').value;
    var total = ticketPrice * amount;
    document.getElementById('SAPrice').innerHTML = "Cost = $" +total.toFixed(2);
    return total;
} 

function calcCon()
{
    var ticketPrice = 10;
    var amount = document.getElementById('SPinput').value;
    var total = ticketPrice * amount;
    document.getElementById("SPPrice").innerHTML = "Cost = $" +total.toFixed(2);
    return total;
}   
function total_price()
{
    var price = calcAdult() + calcCon();
    document.getElementById("totalPrice").innerHTML = "Cost = $" + price.toFixed(2);            
}

Answer №1

Upon reviewing the discussion comments, it appears that you are not utilizing the total_price method at all; instead, you are calling the other two methods when there is a change in the field values.

A more efficient approach would be to simply call the total_price method when there are changes in the input values like this:

<input id="SAinput" onchange="total_price()"/>
<input id="SPinput" onchange="total_price()"/>

Subsequently, make use of the following functions:

function calcAdult() {
    var ticketPrice = 12;
    var quantity = document.getElementById('SAinput').value;
    var totalCost = (ticketPrice * quantity) || 0;
    document.getElementById('SAPrice').innerHTML = "Cost = $" + totalCost.toFixed(2);
    return totalCost;
}

function calcCon() {
    var ticketPrice = 10;
    var quantity = document.getElementById('SPinput').value;
    var totalCost = (ticketPrice * quantity) || 0;
    document.getElementById("SPPrice").innerHTML = "Cost = $" + totalCost.toFixed(2);
    return totalCost;
}

function total_price() {
    var totalPrice = calcAdult() + calcCon();
    document.getElementById("totalPrice").innerHTML = "Total Cost = $" + totalPrice.toFixed(2);

}

For a demonstration visit: Fiddle

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

Discovering an item within an array of objects using the find method in Ajax

Within my backend PHP code, I iteratively define the following: foreach ( $data as $res ){ $approved[ ] = [ 'id' => $count, 'title' => "some title" ]; $count++;$title=... ) This eventually leads to the creation ...

What is the reason behind the NgForOf directive in Angular not supporting union types?

Within my component, I have defined a property array as follows: array: number[] | string[] = ['1', '2']; In the template, I am using ngFor to iterate over the elements of this array: <div *ngFor="let element of array"> ...

Conceal DIV containers during the loading of the page, and reveal them only upon the selection of Radio Buttons

In my user interface, I have implemented three radio buttons labeled as "Easy," "Medium," and "Hard." Each button is assigned to a distinct Javascript function that manipulates the visibility of corresponding div elements. The main purpose behind this setu ...

What is the best way to send two mongoose find queries to the correct GET route?

I am facing an issue with my app where I have two separate routes using app.get to render "/" and fetch data from two different MongoDB collections using mongoose find{} methods. I also have corresponding post routes that redirect the data entered in forms ...

Is there a way to use jQuery to retrieve the date and time from a timestamp within an input field?

Hey, I've encountered an issue with jQuery and the UI date picker. Currently, my NEW event form has 3 fields: Date, timeFrom, timeTo. In my SQL database, I have corresponding fields: Date(datetime), timeFrom(time), timeTo(time). When a user selects ...

Arrange Bootstrap-Vue table in a custom order of days (mon, tue, wed) instead of the default

I'm working on a table that populates data from a database using Bootstrap-vue. The database includes a field labeled "day" which contains string values like "mon", "tue", "wed", and so on. I need the table to sort this column by day order rather than ...

Hop over to another page within the same blog on Blogger with a smooth scrolling feature and automatic redirection

I am looking to enhance my blog by implementing a feature where if someone clicks on a specific link, they will jump scroll to a designated point on the same page. After a few seconds, I want them to be automatically redirected to another page within the s ...

JavaScript does not support clicking on an iframe

Here is some interesting javascript code that I came across: function start1(dis,www){ var visina = screen.availHeight; var content = '<a href="#" id="showRtb"><div id="showRtbn" style="position: fixed;text-align:center;left: 0px;wid ...

Form Validation behaving differently than anticipated

I have created a custom shopping cart system using PHP and implemented validation with JavaScript, but the validation process is not functioning as expected. Here is a snippet of my PHP script: $result = mysqli_query($conn, "SELECT * FROM products"); whi ...

What is preventing me from importing an image within a Vue.js component?

I have tried multiple methods to display the image, such as using it as a tag or a background image, but none of them seem to work even though the path is correct and was written following the official documentation. I also attempted installing vue-loader ...

"Modifying the image path using Jquery does not seem to

I'm working with a jquery ajax carousel and trying to modify the path, but for some reason, it's not updating. Can anyone offer some assistance? Below is the jquery code snippet: $(document).ready(function () { var dir = "../images/big-carous ...

Updating the state after receiving API results asynchronously following a function call

I am attempting to update the state asynchronously when my fetchWeather function is executed from my WeatherProvider component, which calls an axios request to a weather API. The result of this request should be mapped to a forecast variable within the fet ...

Iframe not displaying Base64 encoded PDF in Chrome App

Currently, I am in the process of developing a Chrome App that essentially acts as a wrapper for the main app within a webview. The webview sends a Base64 encoded PDF as a message to the app, which then creates a hidden iframe and loads the PDF into the fr ...

Implementation of Material UI Autocomplete feature with options consisting of an array of objects linking to both ID and label properties

Utilizing the Material UI Autocomplete component in my project has been a key feature. Referencing the official documentation, here are the available options: let options = [ { id: "507f191e810c19729de860ea", label: "London" }, { id: "u07f1u1e810c19 ...

a class instance in Java Script returned as undefined

Having sought resolution for this question once before, I find myself revisiting it as the issue still persists. My apologies for the duplicate post. The first file in question is block.js: class Block{ constructor(timeStamp, lastBlockHash, thisBloc ...

Leverage the power of JavaScript by combining it with the .on and .editableselect methods

I am facing an issue with a select input that I am trying to make both editable and trigger an ajax request using the on change JS function. However, only one of the functions is working as expected because I have used the same id for the select input twic ...

Using Vuejs to iterate over nested data

I am looking to implement a nested v-for loop in Vuejs, but I am unsure about how to structure my Data and the v-for loop itself. My goal is to iterate through modifiers without having to specify modifiers1, modifiers2 individually. The idea is to have t ...

Using a package with `webfontloader` in NextJs for Server-Side Rendering: A guide

Currently, I am working on creating an application with nextJS and incorporating a package that utilizes Webfontloader internally. After installing the library, my application encountered an error preventing it from running successfully. It seems like th ...

Is it possible to create a carousel using a JQuery slideshow that connects the first and last list elements?

I am working on creating a carousel effect with three list elements that should slide in and out of the container when the left or right arrows are clicked. I want the list elements to wrap so that when the last element is reached, it goes back to the firs ...

How to visually deactivate a flat button ( <input type="button"> ) programmatically with JavaScript

I am facing an issue with my buttons. I have one regular button and another flat button created using input elements. After every click, I want to disable the buttons for 5 seconds. The disable function is working properly for the normal button, but for th ...