Numerical computations performed within text fields

I am currently working on a script where I am trying to calculate the total of two different operations and then come up with an overall quote. However, I am facing an issue when it comes to combining these calculations. Please keep in mind that I am relatively new to coding, so there might be some room for improvement in my code. Any suggestions to enhance the code would be greatly appreciated.

<div>
        <fieldset>
            <legend>Printing</legend>
        Number of color pages:<input type="text" id="color" placeholder="Color Pages" onchange="printing();" onchange = "binding();" />
        <input type="text" id="colorprice" readonly="readonly" /><br />
        Number of black and white pages:<input type="text" id="black" placeholder="Black and White Pages" onchange="printing();" onchange = "binding();" />
        <input type="text" id="blackprice" readonly="readyonly" /><br />
        Total Pages:<input type="text" id="pages_total" readonly="readonly" /> <input type="text" id="sum_pages" readonly="readonly" onchange = "suming();"/>
        </fieldset>

    </div>

<div>
        <fieldset>
            <legend>Binding</legend>
            Number of Hardbooks: <input type="text" id="books" placeholder="Number of Hardbooks" onchange="binding();" />
            <input type="text" id="books_price" readonly="readonly" /><br />
            Number of Softbacks: <input type="text" id="softback" placeholder="Number of Softbacks" onchange="binding();" />
            <input type="text" id="soft_price" readonly="readonly" /><br />
            Total Bindings: <input type="text" id="total_bindings" readonly="readonly" /><input type "text" id="total_price" readonly="readonly" />
        </fieldset>
    </div>

<p>Final quote:<input type="text" readonly="readonly" id="quote" /></p>

function printing() {
                var blackPrice;
                var colorPrice;
                var printBlack = new Array(0.10, 0.08, 0.06, 0.05);
                var printColor = new Array(0.40, 0.35, 0.30, 0.25);


                var colorPages = parseInt(document.getElementById("color").value);
                var blackPages = parseInt(document.getElementById("black").value);

                if (colorPages < 11) {
                colorPrice = colorPages * printColor[0];
                    }
                else if (colorPages >= 11 && colorPages < 51){
                colorPrice = colorPages * printColor[1];
                    }
                else if (colorPages >= 51 && colorPages < 101){
                    colorPrice = colorPages * printColor[2];
                    }
                else {
                    colorPrice = colorPages * printColor[3];
                    }



                if (blackPages < 11) {
                blackPrice = blackPages * printBlack[0];
                    }
                else if (blackPages >= 11 && colorPages < 51){
                blackPrice = blackPages * printBlack[1];
                    }
                else if (blackPages >= 51 && colorPages < 101){
                blackPrice = blackPages * printBlack[2];
                    }
                else {
                blackPrice = blackPages * printBlack[3];
                    }

                var pagesTotal = colorPages + blackPages;

                var printSum = blackPrice + colorPrice;


                document.getElementById("colorprice").value = "$" + colorPrice.toFixed(2);
                document.getElementById("blackprice").value = "$" + blackPrice.toFixed(2);
                document.getElementById("sum_pages").value = "$" + printSum.toFixed(2);
                document.getElementById("pages_total").value = pagesTotal;

                return printSum;

}



function binding(){

var softbackPrice;
var hardbookPrice;
var hardBooks = new Array(37.50, 23.50);
var softBacks = new Array(3.75, 4.00, 4.25, 4.50, 4.75, 5.00, 5.25);
var noBooks = parseInt(document.getElementById("books").value); 
var noSoftBacks = parseInt(document.getElementById("softback").value); 
var colorPages = parseInt(document.getElementById("color").value);
var blackPages = parseInt(document.getElementById("black").value);
var totalPages = colorPages + blackPages;

if (noBooks == 1) { 
    hardbookPrice = hardBooks[0];
    }
else {
        hardbookPrice = (hardBooks[1] * (noBooks - 1)) + hardBooks[0];
    }

if (totalPages <= 50) {
    softbackPrice = softBacks[0] * noSoftBacks;
    }
else if (totalPages > 50 && totalPages <= 100) {
    softbackPrice = softBacks[1] * noSoftBacks;
    }
else if (totalPages > 100 && totalPages <= 150) {
    softbackPrice = softBacks[1] * noSoftBacks;
    }
else if (totalPages > 150 && totalPages <=200) {
    softbackPrice = softBacks[2] * noSoftBacks;
    }
else if (totalPages > 200 && totalPages <= 250) {
    softbackPrice = softBacks[3] * noSoftBacks;
    }
else if (totalPages > 250 && totalPages <= 300) {
    softbackPrice = softBacks[4] * noSoftBacks;
    }
else if (totalPages > 300 && totalPages <= 350) {
    softbackPrice = softBacks[5] * noSoftBacks;
    }
else {
    softbackPrice = softBacks[6] * noSoftBacks;
}   



var totalPrice = softbackPrice + hardbookPrice;
var bindingsTotal = noSoftBacks + noBooks;


document.getElementById("books_price").value = "$" + hardbookPrice.toFixed(2);
document.getElementById("soft_price").value = "$" + softbackPrice.toFixed(2);
document.getElementById("total_bindings").value = bindingsTotal;
document.getElementById("total_price").value = "$" + totalPrice.toFixed(2);


return totalPrice;

}

function totalSum() {
var totalPrinting = printing();
var totalBinding = binding();
var subtotal = totalPrinting + totalBinding;
document.getElementIdBy("quote").value = subtotal;
}

Answer №1

Check out the solution that is currently working. http://jsbin.com/OKvFr/4/

= should be added for type in the following code snippet

<input type="text" id="total_amount" readonly="readonly" />

Answer №2

I've found a solution that works for me most of the time, you can check it out here: http://jsfiddle.net/UHnRL/

One issue I encountered was with the initial calculation when using the onchange event, as the number of pages would sometimes turn into 'NaN' after applying parseInt. To address this, it's recommended to set the default value to zero if the text box is empty.

To handle this problem, you can utilize the isNaN function to ensure accurate calculations:

var colorPages = parseInt(document.getElementById("color").value);
var blackPages = parseInt(document.getElementById("black").value);

if (isNaN(colorPages))
{
    colorPages = 0;
}

if (isNaN(blackPages))
{
    blackPages = 0;
}

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

Disable or set input text to read-only in Internet Explorer 9 and earlier versions using JavaScript or jQuery

Can anyone offer any suggestions on how to accomplish this task? I attempted using JavaScript with the code below, but it did not yield the desired results. element.readOnly="true"; element.readonly="readonly"; element.disabled="disabled"; I also tried ...

The functionality of using an Ajax call to invoke a php function on the same page is not functioning correctly

I am facing an issue where Ajax is not working in the same PHP file as the PHP function I want to call. My goal is to have a button that, when pressed, will trigger the function without reloading the page. I have placed my Ajax script at the bottom and the ...

Trying to draw a comparison between a text box and an individual element within

I am having some difficulty comparing user-entered text in a textbox with an element in an array. function checkUserInput() { var str = imageArray[randomNumber]; var index = str.indexOf(document.getElementById('textBox').value); ...

Strange Scrolling Issues in Blackberry Webworks when Using Touchscreens

Within my Blackberry Webworks app designed for Smartphones OS 6, 7, and 7.1, there is a portion of code that looks like this: <div style="width:100%; height:100%; overflow:hidden;"> <div style="overflow:auto;height:100px;width:100%;"> ...

I'm experiencing an issue when trying to align TextPath to the center in an SVG file - a certain character

When using the startOffset or text-anchor attributes, I noticed that some characters are missing. How can I fix this issue? Thank you. It appears that in this scenario, the characters `1234` are missing. <svg xmlns="http://www.w3.org/2000/svg" versi ...

Unable to alter the pagination's selected page color to grey with material UI pagination components

Currently, I am implementing pagination using material UI. While I have successfully changed the page color to white, I am facing difficulty in changing the selected page color to grey. This issue arises because the background color is dark. import React, ...

Connect the attributes of one object to the properties of another object

I am looking to create a new object in Javascript and assign its property some values from another object. I want this assignment to be like 'pass by reference' in C++. In the code snippet below: var object1 = { 'obj1' : { &ap ...

Tips for retrieving specific values from drop-down menus that have been incorporated into a dynamically-sized HTML table

How can I retrieve individual values from dropdown menus in HTML? These values are stored in a table of unspecified size and I want to calculate the total price of the selected drinks. Additionally, I need the code to be able to compute the price of any ne ...

Steps to sending a request with a custom user agent

In my Angular app, I have successfully implemented server-side pre-rendering with the condition that it will only pre-render if a search bot is sending the request. Now, I need to verify if everything is pre-rendered correctly. However, when I visit my w ...

Align two DIVs in the correct layout: One as a sidebar that remains fixed, and the other as an expanding element

I am currently working on a code snippet to build a basic website featuring two main sections: a sidebar and the main content: html, body { height: 100%; margin: 0; } .container { display: flex; flex-direction: row; height: 100%; } .sidebar { ...

AngularJS restructured the homepage to function as a shell page instead of the traditional index page

As a newcomer to angularJS, I am learning that it is typically designed for Single Page Applications. Most example logins I come across define the index.html as the main page, with the ng-view portion contained within. However, in my situation, the Login ...

leveraging the default browser behavior for the href and target attributes within an <a> element in Angular 2

How can the behavior of a simple anchor tag in Angular 2 be implemented without being overridden by the routing module? <a href="some url" target="_whatever"> It is crucial to prevent the routing module from highjacking the URL using the base href. ...

What is the origin of the second parameter in an arrow function that returns another arrow function in a React component with Redux?

I'm having trouble understanding where the (val) parameter is coming from in the returned arrow function. I understand that max/minLength is an arrow function taking an argument set on the input field (3 and 25), and it returns another arrow function ...

What is the best way to retrieve the values from the labels for two separate buttons?

I designed a pair of buttons with a single label below. Both buttons acted as standalone entities. <label for="buttons" class ="val">0</label> <input class="btn btn-primary button1" type="button" ...

What is the best way to establish a default rejected promise behavior for all of my Express middleware functions?

Using promises within express middleware and wanting to switch to async/await methods. app.get('/data1',async function(req,res) { data = await getData1(); // Error occurs here res.send(data) }) app.get('/data2',async function(r ...

What is preventing me from executing node.js and socket.io within a screen or utilizing Forever?

I'm encountering an issue with running nodejs in a screen. The problem arises when I leave the screen and no sockets are connected. The next person trying to connect will face an error message until the screen is reopened using screen -R node. Once th ...

Is there a way to generate a button that displays the subsequent 5 outcomes from the database without navigating away from the current

I am looking to implement a button on my webpage that, once clicked, will load the next set of five questions from my database. I prefer not to use pagination or the GET method to prevent users from navigating back to previously answered questions. My goa ...

Issues with Bootstrap's hamburger menu not functioning properly when clicked

Can't seem to get my hamburger button working. I've followed the bootstrap documentation and ensured that Bootstrap and jQuery are in the correct order, but still no luck. Any suggestions on what could be causing this issue? Are my links misplace ...

Issue with react-addons-css-transition-group and multiline TextFields in Material-UI TextField

If a TextField with multiline is nested inside a react-addons-css-transition-group, it seems to disrupt the show transition. Any suggestions on how to handle this situation effectively? Check out my code snippet here: https://codesandbox.io/s/material-dem ...

Repeated failures in the CodeIgniter JavaScript function

Currently I am developing a donation store using CodeIgniter. I have been focusing on implementing the cart functionality, and have created a small card to display the store items. The card allows users to add items to their cart using an AJAX request to p ...