Transferring the output of a Javascript function to display in a different location

One of the challenges I'm facing involves a function that calculates the total cost of tickets based on user selection from a dropdown list. The price per ticket is stored in my database and retrieved when needed.

The function itself is functional:

function quantityChange(selElem) {
//Get the selected value from the dropdown list       
var quantity = $('#showQuantity option:selected').val();
//Retrieve ticket price from 'ticket' table
var ticket = parseInt(document.getElementById('ticketPriceHidden').value);
//Obtain venue information
var venue = document.getElementById('venuePlaceHidden').value;
//Multiply quantities to get total cost
var total = quantity * ticket;

document.getElementById('summary').innerHTML= 'You have chosen'+ ' ' + quantity + ' ' + 'tickets @' + ' ' + venue + ' = ' + ' ' + ' £' + total;
}

This function is triggered within a div labeled 'ticket'. Once the user views the calculated total and proceeds by clicking a 'continue' button, the 'ticket' div is hidden and replaced with a 'delivery' div to retain the result.

Now, I am faced with another challenge: I need to display the result of the quantityChange(selElem) function within a new div called 'summary'. Is there a way to achieve this?

Your assistance would be highly appreciated. Thank you.

Answer №1

One way to add flexibility is by passing the ID of the element where you want the text displayed as a parameter in the function:

function updateQuantity(elementId) {
    // Get the selected quantity from the dropdown
    var quantity = $('#showQuantity option:selected').val();
    // Obtain the ticket price from the hidden field
    var ticket = +$('#ticketPriceHidden').val();
    // Retrieve the venue information
    var venue = $('#venuePlaceHidden').val();
    // Calculate the total cost
    var total = quantity * ticket;

    $('#' + elementId).html('You have selected' + ' ' + quantity + ' ' + 'tickets at' + ' ' + venue + ' for a total of' + ' ' + '£' + total);
}

You can then call this function like:

updateQuantity('summary');

To make it even more versatile, you can have the function return all the calculated values:

function updateQuantity() {
    // Obtain the selected quantity
    var quantity = $('#showQuantity option:selected').val();
    // Get the ticket price from the hidden field
    var ticket = +$('#ticketPriceHidden').val();
    // Retrieve the venue info
    var venue = $('#venuePlaceHidden').val();
    // Calculate the total cost
    var total = quantity * ticket;

    return {
        venue: venue,
        quantity: quantity,
        ticket: ticket,
        total: total
    };
}

Then, handle the output in the calling function:

var data = updateQuantity();

$('#summary').text('Total payment due: £' + data.total);

This approach allows for customization in displaying the data without hardcoding it into the value computation function.

Answer №2

Transform this into a versatile function that outputs a result.

function calculateSum()
{
var firstNumber = 0;
var secondNumber = 1;
return firstNumber + secondNumber;
}

document.getElementById("result").innerHTML = "The calculated sum is: " + calculateSum();

The content of the element with an id of "result" would display:

The calculated sum is: 1

Answer №3

Here are some useful instructions for you.

To start, a div is generated in the first line of code.

Next, your function's outcome is placed within that newly created div.

Lastly, the div is attached to an element with the designated id "xxx".

var newDiv = document.createElement("div");
newDiv.innerHTML = resultOfFunction;
document.getElementById("xxx").appendChild(newDiv);

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

Angular JS: Implementing a click event binding once Angular has completed rendering the HTML DOM

Exploring AngularJS for the first time, I've researched extensively but haven't found a satisfying solution. My goal is to retrieve data from the server and bind it to HTML elements on page load. However, I also need to bind click events to these ...

Obtaining worth from an entity

I have a collection of objects structured like so: [Object { image = "images/item-1.png" , heading = "Careers" , text = "Lorem ipsum dolor sit a...ctetur adipiscing elit." }, Object { image = "images/item-2. ...

What is the method to retrieve the local filepath from a file input using Javascript in Internet Explorer 9?

I'm experiencing some issues with the image-preview function on IE9, similar to the example photo shown. This method is not functioning properly and throwing an error in IE9, while it works perfectly fine in IE6-8. I am looking for a way to retrieve ...

Executing both JavaScript Promise .then() and .catch concurrently

I've been working on converting my WordPress comments into an ajax-driven system. Everything was going smoothly until I encountered a problem with the .catch() method triggering right after the .then() method. Below is the code snippet... Ajax engi ...

Element could not be located following successful login process

Currently, I am in the process of developing automation scripts using NightWatchJS. My test scenario involves a few basic steps: Launching a URL Logging in Verifying elements on the page Ensuring the presence of elements within an iframe The login page i ...

A configuration for ".node" files is missing: specifically, the loader for node_modules/fsevents/fsevents.node in a project using Vite

Everything was running smoothly in my Vite + React project until last week when out of nowhere, I encountered this error: No loader is configured for ".node" files: node_modules/fsevents/fsevents.node node_modules/fsevents/fsevents.js:13:23: 1 ...

Interactive HTML5 Web Application File Selector

After conducting thorough research, it is important to note that I am well-versed in the security implications of this client-side application which utilizes JavaScript, Vue, and pure HTML5. To initiate the file dialog, I employ a hidden input type file. ...

Tips for deleting multiple objects from an array in angular version 13

I am facing an issue where I am trying to delete multiple objects from an array by selecting the checkbox on a table row. However, I am only able to delete one item at a time. How can I resolve this problem and successfully delete multiple selected objects ...

Is there a way to simulate a KeyboardEvent (DOM_VK_UP) that the browser will process as if it were actually pressed by the user?

Take a look at this code snippet inspired by this solution. <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <script> $(this). ...

"Enhance your web development skills by mastering jQuery alongside the

It's curious that jQuery doesn't support the use of the "+" sign. You can see how it functions with "1" and "3", but not with "2+". Just hover your mouse over each div to experience it. <div id="div-2+"></div> JSFiddle $('a. ...

Can you explain the significance of the error message stating "XMLHttpRequest.timeout cannot be set for synchronous http(s) requests made from the window context"?

I'm experiencing some timeouts with a synchronous XML HTTP request in Safari on my Mac. In an attempt to fix this issue, I added a timeout setting like this: req.open(this.method, fullURL, this.isAsync); req.setRequestHeader('Content-Typ ...

Angular 14 debug error: Incorrect base path setting

Whenever I go for a run, I have to specify a starting point such as /pis/ ng serve --serve-path /pis/ Even after following these instructions, nothing seems to load. Can anyone lend a hand with setting a starting point in the ng serve process? ...

Vue select is causing the selected choice of another selector to be influenced

Currently, I am facing an issue with a table displaying a specific Nova resource. The problem lies in the selectors within each row of the table - when one selector is changed, all other selectors automatically mirror that change. This behavior seems to be ...

How can I create a notification popup triggered by a button click with Ajax and Javascript?

I'm in the process of developing a website that involves notifications, but I am unsure how to display them when a button is pressed. For example, clicking "Show Weather" should trigger a notification to appear in the bottom corner of the page. https ...

Could a class method be accessed from outside a nested handler method in JavaScript?

I am trying to make an XMLHttpRequest to a server using JavaScript. In the handler function, I need to call a method from the surrounding class. Is there a way to achieve this? Understanding how this works in JavaScript can be confusing. I have experiment ...

Using PHP to pass values from a MySQL database to JavaScript

hello, $i=0; while($row = $result->fetch_assoc()) { echo " <tr><td>".$row["Number"]."</td><td>".$row["MusikName"]." ".$row["MusikURL"]."</td></tr>"; This portion is successful...it displays -&g ...

Using Javascript to make a nested JSON api request that includes several query parameters

I am currently working on creating an API for my upcoming website, but I am facing difficulty in obtaining multiple query results using the same URL in an express app. Sample data: var data = [{ articles : [{ id : '0', url : ...

Monitor the $scope within a factory by utilizing the $http service in AngularJS

I'm attempting to monitor a change in value retrieved from a factory using $http. Below is my factory, which simply retrieves a list of videos from the backend: app.factory('videoHttpService', ['$http', function ($http) { var ...

"RecognitionAudio variable missing" and "InactiveRpcError occurred" [Utilizing the Google text-to-speech API]

I have a goal I'd like to achieve. A user communicates with a web browser. The web browser records the user's voice as a WAV file using Recorder.js and sends it to a server running on Google App Engine Standard environment with Python 3.7. The ...

The HTML div captured with html2canvas is incomplete

I am currently developing a meme editor website utilizing the html2canvas library available at Below is the HTML code for the div I aim to capture: <div class="container"> <div id="theUserMeme"> <div class=& ...