What is the process for declaring a variable and then using it within a concealed input field?

I have a JavaScript code that performs mathematical calculations, and I need to extract the final result to include it in a form. My plan was to utilize an

<input type="hidden" name="new total">
field to store this result. I am looking to retrieve the information from the "New Total" field. You can view my JavaScript code in action here: http://jsfiddle.net/danielrbuchanan/yjrTZ/5/

var prices = [];

function remove(arr, itm){
    var indx = arr.indexOf(itm);
    if (indx !== -1){
        arr.splice(indx, 1);
    }
}

function calculateSelectedDues(checkbox, amount) {
    if (checkbox.checked === true) {
        prices.push(amount);
    } else {
        remove(prices, amount);
    }

    var total = 0;
    for (var i = 0, len = prices.length; i < len; i++)
        total += prices[i];

    var min = prices.slice().sort(function(a,b){return a-b})[0];
    if(typeof min === 'undefined') min = 0;

    var withDiscount = total - min;
    var discountAmount = withDiscount - total;

    //document.grad_enroll_form.total.value = total;
    document.querySelector("#value").innerHTML = "Total: $"+total+'<br>';
    document.querySelector("#value").innerHTML += "Discount: $"+discountAmount+'<br>';
    document.querySelector("#value").innerHTML += "New total: $"+withDiscount+'<br>';
}

Although it appears straightforward, I seem to be struggling to figure it out.

Answer №1

It seems like what you're looking to do is assign a variable to an input value, which can be done using the following code:

JavaScript:

document.getElementById("newTotal").value = updatedValue;

HTML:

<form>
    <input id='newTotal' type='hidden' name='NewTotal' value='' />
</form>

I hope this solution works for you.

Answer №2

<input type="hidden" id="new_total_amount" name="new_total_amount">
<!-- ensure no spaces in name and id attributes -->

Insert the above code snippet at the conclusion of the calculateSectedDues function.

document.getElementById('new_total_amount').value = withDiscount;

Answer №3

There are a couple of pathways you can take.

Option 1: Using jQuery

Add a visible div in any way that suits your needs. Attach onChange() events to your input fields to trigger the calculation.

<div id="finalValue"></div>

<script language="javascript">
$(function() {
    $("form input").change(function() {
        calculateSectedDues($("#checkboxid"), $("#amountid").val());
    });
});
</script>

In the calculateSectedDues() function, append this at the end:

$("#finalValue").html("Total: $" + total + "<br />Discount: " + discountAmount + "<br />New Total: " + withDiscount + "<br />");

Option 2: Without using jQuery

<div id="finalValue"></div>

<script language="javascript">
function bindEvent() {
    calculateSectedDues(document.getElementById("checkboxid"), document.getElementById("amountid").value);
}
window.onload = function()
{
    var elJ = document.getElementsByTagName("input");
    for (var i=0;i<elJ.length;i++) {
        elJ[i].addEventListener('change',bindEvent,false);
    }
}
</script>

In the calculateSectedDues() function, add this at the end:

document.getElementById("finalValue").InnerHtml("Total: $" + total + "<br />Discount: " + discountAmount + "<br />New Total: " + withDiscount + "<br />");

Is this the outcome you are aiming for?

Remember to also perform the calculation on the Server Side and not solely depend on JavaScript. Displaying the information beforehand is mainly for user notification, as hidden total fields could be exploited through front-end manipulation techniques.

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

How can I efficiently map an array based on multiple other arrays in JavaScript/TypeScript using ES6(7) without nested loops?

I am dealing with 2 arrays: const history = [ { type: 'change', old: 1, new: 2 }, { type: 'change', old: 3, new: 4 }, ]; const contents = [ { id: 1, info: 'infor1' }, { id: 2, info: 'infor2' }, { id: ...

Retrieve progress with easing using jQuery's animate() function

At the moment, I'm utilizing this code to create an animation for a bar-graph-inspired element: $('.anim').animate({ right: `${100-(e/max*100)}%`, backgroundColor: colors[0] },{ duration: 1500, easing: 'easeInQuart&apos ...

Steps to automatically populate the dropdown upon page load

Hello, I have a question regarding setting a value to a dropdown list in JavaScript. Currently, I am trying to execute this function during the onload event of the body tag. However, I am facing issues with setting the value. Below is the code: function s ...

Tracking progress within an HTML table

I am facing an issue with a table that is designed to display progress bars for each method or task stored in the database. These progress bars are determined by two dates: the startDate and endDate. However, I have noticed that the progress bar only funct ...

Tips for adjusting the size of an HTML canvas to fit the screen while preserving the aspect ratio and ensuring the canvas remains fully visible

I'm working on a game project using HTML canvas and javascript. The canvas I am using has dimensions of 1280 x 720 px with a 16:9 aspect ratio. My goal is to have the game displayed at fullscreen, but with black bars shown if the screen ratio is not 1 ...

A reliable approach for dynamically altering SVG graphics

It seems like IE10 does not support CSS transformations for SVGs, only attribute transformations. Here is an example: <svg><rect id="myrect" width="200" height="200"></rect></svg> setTimeout(function() { var r = document.getE ...

Saving form blueprints and operations in a Data Repository

My team and I are working on a sophisticated web application with a complex back end. We have hundreds of form schemas paired with their corresponding return functions, which are triggered upon form submission. These JSON objects dynamically generate forms ...

How can NodeJS functions leverage parameters such as req, res, and result?

As a newcomer to JS, particularly Node and Express, I am in the process of learning how to build an API through tutorials. Along the way, I am also exploring various special features of JS such as let/const/var and arrow functions. One common pattern I no ...

Launching apps from the background using React Native deep linking

After enabling deep linking, everything seems to be working fine when the application is opened. However, I've encountered an issue when trying to open the app from a background state using the URL moderatorapp://hello. While it logs the correct URL, ...

tips for correctly importing source files into jasmine-node testing framework

Currently, I am utilizing the jasmine spec library in combination with the jasmine-node runner for node.js. My main query revolves around the correct method to execute tests using a command in the CLI that encompasses both source files and spec files. Wit ...

Validation is a must in Angular 2

I am facing an issue with the default required validator in angular forms. My form has one input field and a submit button. There are two important files: example.form.ts example.form.template.html Here is my code setup: In the .ts file, I create ...

Navigating and extracting nested JSON properties using JavaScript (React)

I am currently working with a nested JSON file that is being fetched through an API. The structure of the JSON file looks something like this: { "trees":{ "name":"a", "age":"9", "h ...

Ways to halt the setInterval function after executing a specific function within it

Currently, I have a condition in place to verify if I am on a specific URL. If this condition is true, the setInterval() function will begin checking for a particular element on the webpage. Once the element is located, a designated function will be exec ...

What is the most effective way to reduce the length of user input in a textarea and set limits on both the maximum

Is it possible to adjust the length of input and textarea and show the remaining words left? My goal is to have a total length of 200 characters for both input and textarea fields. <input type="text" id="b" name="b" value="Hi world !" maxlength="50"&g ...

Automatic line breaks within a JavaScript code can be achieved by using

I need help formatting this text: hello everyone. My name is PETER. hahahah ahahah .... If I have a fixed width, how can I automatically line break the text to look like this: hello everyone. My name is PETER. hahahah ahahah ...

Sending data from the View to the Controller in a Razor MVC3 application involves passing a model along with

Within my view, there's a form representing my View model with multiple fields. I aim to generate a list of links for pagination purposes that will not only redirect to a specific page but also send the input data from the form along with it. The Java ...

Creating a 3D visualization with three.js

My project requires me to create a 3D scatter graph using three.js. I have attempted to implement the code provided below. While the code is functional, the resulting graph appears more like a 2D representation. Adjusting the camera position can add depth ...

Is the size of the node_modules directory a factor in the cold start performance of cloud functions?

In my understanding, it is best practice to only import necessary modules in the global scope of the index file to minimize cold start times. However, I am still unsure whether the size of the node_modules folder (or the number of dependencies listed in t ...

Solving the Cross-Origin Resource Sharing problem in AngularJS

While using the http dependency in AngularJS and setting headers for CORS, I am encountering an error. Please check the console.log for more information on the error. The error message reads: "XMLHttpRequest cannot load . Response to preflight request doe ...

Learn how to deactivate the pause button with just one click and re-enable it once the popup appears using Angular2 and Typescript

Can anyone assist with solving an issue I am facing with a timer and a pause button? I need the pause button to be disabled once clicked, until a popup appears, then it should become enabled again. My code snippet is provided below: HTML: <button md-i ...