Embedding a JavaScript variable into a form input field

I am facing a challenge in passing a JavaScript variable through a hidden form to a PHP script. While I have no issue passing it to PHP, I am struggling to integrate the variable into the form.

function calculate() {    
            var radio1 = document.forms["calcForm"].v1;
            var radio2 = document.forms["calcForm"].v2;

            var getf1 = getSelectedRadio(radio1);
            var getf2 = getSelectedRadio(radio2);

            var f1 = radio1[getf1].value;
            var f2 = radio2[getf2].value;

            var resultat = document.getElementById("resultat");
            var total = (parseInt(f1) + parseInt(f2)).toFixed(0);
            resultat.value = total; //used to show value in another input-field
            }

document.contactForm.formTotal.value = total;

The issue arises with the last line as it does not accept `total`. The `calculate` function works flawlessly - as does everything else when I substitute `total` with a simpler variable like `var x= 10;`

I am looking for a solution to set `document.contactForm.formTotal.value` to the value of `total`. It seems that there might be difficulty retrieving some values from the function, but my knowledge of JavaScript is limited, hindering me from finding a resolution.

Answer №1

The variable "Total" is specifically declared within the function scope, preventing its usage in assignments outside of this function.

One solution is to either relocate the assignment statement inside the function or modify the function to return the value instead.

Answer №2

It is important to note that the variable total is currently outside of the function's scope. One possible solution is to declare it within the function itself, although a more efficient approach would be for the function to return a value. Here's how it can be implemented:

function calculate() {    
        var radio1 = document.forms["calcForm"].v1;
        var radio2 = document.forms["calcForm"].v2;

        var getf1 = getSelectedRadio(radio1);
        var getf2 = getSelectedRadio(radio2);

        var f1 = radio1[getf1].value;
        var f2 = radio2[getf2].value;

        var resultat = document.getElementById("resultat");
        var total = (parseInt(f1) + parseInt(f2)).toFixed(0);
        return resultat.value; // This will display the value in another input field.
}

var total = calculate();

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

Sort the array and organize it by frequency

Given the input array: array = [ 1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20 ] The expected output is: [ [ 1, 1, 1, 1 ], [ 2, 2, 2 ], 4, 5, 10, [ 20, 20 ], 391, 392, 591 ] Using the following function to generate the result: var array = [ ...

Leaving Facebook with onbeforeunload functionality

Within my AngularJS application, I am utilizing the Facebook SDK. When I trigger FB.logout() upon clicking the logout button, it functions correctly: $scope.logout = function() { FB.logout() } However, I also aim to log out from Facebook when ...

Encountering issues with Office.context.document.getFileAsync function

I am experiencing a strange issue where, on the third attempt to extract a word document as a compressed file for processing in my MS Word Task Pane MVC app, it crashes. Here is the snippet of code: Office.context.document.getFileAsync(Office.FileType.Co ...

Session data becomes null after navigation in multi-page apps using Meteor and Backbone

Greetings everyone! I am currently developing a web application using meteorjs. Thanks to backbone, I have successfully implemented a multipage feature in my web app. Take a look at my router.js code below: Router = { uri: _.compact(window.location.pa ...

Disable menu bar | customize menu bar in electronJS

I am developing an Angular application with Electron.js. Due to the specific design requirements of my app, which is browser-based, I do not require or want the default Electron.js menu or menu bar to be displayed. Is there a way to remove it from my app ...

Using *ngFor index value results in an error message saying "The call stack size has reached its maximum limit."

Check out this StackBlitz demo I have a simple view where I'm looping over HTML using Angular's *ngFor directive. To show more or less content, I'm using the ngx-bootstrap collapse component. The problem is that when I collapse one button, ...

Is there an easy method to verify if the local storage is devoid of any data?

Query is named aptly; seeking to verify in a conditional statement. ...

Modifying `msg.sender` in Solidity and Ether.js

I have a Smart Contract written in Solidity. Within this contract, there is a function called makeMarketItem. function makeMarketItem( address nftContract, uint256 tokenId, uint256 price ) public payable nonReentrant { IERC721(nftContract). ...

Tips for resolving the "unsafe-eval" issue in Vue3 on the client-side platform

My app is built using Express, cors, and helmet. I have incorporated Vue3 on the client-side only, with the library file being self-hosted in the public folder. To add the module to the client-side, I simply include the following script: <script type=&q ...

Show where the image should be placed according to the coordinates of the mouse click

My project begins with a blank canvas, prompting the user to click anywhere on the page to reveal an image. My goal is to show an image at the exact location where the user clicks. Although I can successfully trigger an image to appear in the corner of the ...

JSON data is returned as Object Object

Trying to work with a JSON object and need to stringify it for localStorage: $http.post('http://localhost:8000/refresh', { name: $scope.name, email: $scope.email, token: $rootScope.devToken, platform: ionic.Platform.platform() }).then( ...

Excessive ajax requests occurring when the options in the form are altered

My website contains two main sections: (1) search criteria, which include selection boxes in a form used to access database information, and (2) a div where the results are displayed. The initial page load serializes default values from the form and sends ...

Function for adding numbers in Javascript with currying

Can you help me solve this interesting problem? I need a javascript function that can return the sum of all arguments passed to it, even when called multiple times. I have identified different ways in which the function can be called - sum(1, 2, 3, 4); ...

What might be causing my list item to execute functions that it shouldn't be?

Greetings! I've recently developed a list component in React Native specifically for my settings page. My goal is for each component on the settings page to have a function, although in some cases it may not be necessary. To achieve this, I have set ...

Sending a property as a parameter to a different component through Vue's router-link

I have a component designed to showcase recipes in a list format. Each recipe is rendered using a separate component from an array of recipes. I am currently attempting to pass the recipe object from one component to another component using Router-Link ...

How can I make child events affect the state of the parent component in ReactJs?

I have developed a menu component in reactjs. The parent component includes a method called "handleClick" which controls the opening and closing of the menu by toggling its "open state". Now, I am attempting to pass a click event from the child component ...

Having trouble loading a static image using the [email protected] component via webpack

I am struggling to display a static image in my component called Top.js. To import the image, I have used the following code in Top.js: import logo from './images/logo.png' The path for logo.png is frontend/src/images/logo.png. Next, I tried ...

After deleting all the duplicates, the array is now empty

I've been working on removing duplicate entries from an array of objects, specifically targeting instances where the infoPageId appears more than once. Initially, everything was running smoothly with static data. However, after switching to calling m ...

Handling multiple promises in AngularJS is a common challenge that developers face

I am currently in the process of developing an AngularJS controller that needs to work with multiple promises, each returning a boolean value. The aim is to determine a final boolean value based on these individual results. If all returned values are true, ...

Guide to implementing a real-time countdown timer for days, hours, minutes, and seconds leading up to a specific date and time with JavaScript

Implement a dynamic countdown timer in JavaScript that counts up to a specific date. See the example image for reference: here ...