Error: The if statement is not providing a valid output

I am currently developing a basic price calculator that calculates the total area based on user input fields. While most of the program is functioning correctly, I am encountering an issue with the if statement that is supposed to determine the price rate based on the total sqin value. At the moment, it only applies to the Economy selection in the first drop-down menu. The other selections have fixed values and are working as expected. Any guidance on this matter would be highly appreciated, as I am still relatively new to JavaScript.

/*eslint-env browser*/

var mytotalsq;

function getEconPrice() {
  var EconPrice = 0;
  
  if (mytotalsq <= 199) {
    return EconPrice.value = .40;
  }
  
  if (mytotalsq >= 200 && mytotalsq <= 299) {
    return EconPrice.value = .22;
  }
  
  return EconPrice;
}

var vinyl_prices = new Array();
vinyl_prices["None"] = 0;
vinyl_prices["Econ"] = getEconPrice();
vinyl_prices["Inter"] = .25;
vinyl_prices["HPerf"] = .35;
vinyl_prices["HiTack"] = .75;
vinyl_prices["Ref"] = .75;

var laminate_prices = new Array();
laminate_prices["None"] = 1;
laminate_prices["NoLam"] = 1;
laminate_prices["StanLam"] = 1.43;
laminate_prices["HPLam"] = 1.7;

function getStickerPrice() {
  var StickerPrice = 0;
  var theForm = document.forms["stickerform"];
  var selectedVinyl = theForm.elements["vinyl"];
  StickerPrice = vinyl_prices[selectedVinyl.value];
  return StickerPrice;
}

function getLaminatePrice() {
  var LaminatePrice = 0;
  var theForm = document.forms["stickerform"];
  var selectedLaminate = theForm.elements["laminate"];
  LaminatePrice = laminate_prices[selectedLaminate.value];
  return LaminatePrice;
}

function calculateTotal() {
  var myheight = document.getElementById('height').value;
  var mywidth = document.getElementById('width').value;
  var myquan = document.getElementById('quan').value;
  var totalsq = document.getElementById('totalsq');
  
  mytotalsq = mywidth * myheight * myquan;
  totalsq.value = mytotalsq;
  
  var stickerPrice = mytotalsq * getStickerPrice() * getLaminatePrice();
  var divobj = document.getElementById('totalPrice');
  divobj.style.display = 'block';
  divobj.innerHTML = "Total $" + stickerPrice;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <title>RMSticker Pricing</title>
  <script type="text/javascript" src="js/stickercalc.js"></script>
  <link href="css/sticker.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <div id="wrap">
    <form action="" id="stickerform" onsubmit="return false;">
      <div>
        <div class="cont_order">
          <fieldset>
            <legend>RMSticker</legend>
            <label>Height</label>
            <input id="height" type="text" />
            <label>Width</label>
            <input id="width" type="text" />
            <label>Quantity</label>
            <input id="quan" type="text" oninput="calculateTotal()" />
            <input id="totalsq" name="totalsq" type="text" />
            <br/><br/>
  
            <label>Vinyl</label>
  
            <select id="vinyl" name='vinyl' onchange="calculateTotal()">
              <option value="None">Select Vinyl</option>
              <option value="Econ">Economy</option>
              <option value="Inter">Intermediate</option>
              <option value="HPerf">High Performance</option>
              <option value="HiTack">High Tack</option>
              <option value="Ref">Reflective</option>
            </select>
            <br/><br/>
  
            <label>Laminate</label>
  
            <select id="laminate" name='laminate' onchange="calculateTotal()">
              <option value="None">Select Laminate</option>
              <option value="NoLam">None</option>
              <option value="StanLam">Standard</option>
              <option value="HPLam">High Performance</option>
            </select>
  
            <br/><br/>
  
            <label>Select Finish</label>
            <label class='radiolabel'><input type="radio"  name="selectedfinish" value="Matte" onclick="calculateTotal()" />Matte</label><br/>
            <label class='radiolabel'><input type="radio"  name="selectedfinish" value="Satin" onclick="calculateTotal()" />Satin(Only available on laminated stickers)</label><br/>
            <label class='radiolabel'><input type="radio"  name="selectedfinish" value="Gloss" onclick="calculateTotal()" />Gloss</label><br/>
  
            <div id="totalPrice"></div>
  
          </fieldset>
        </div>
  
                       
      </div>
    </form>
  </div>
  <!--End of wrap-->

Answer №1

The primary issue lies in the timing of your code execution. The lines responsible for setting up a new array and populating it run immediately, before the user has input any data. Consequently, the array remains empty when you try to access information from it.

To resolve this issue, moving the lines that populate the arrays (while keeping the declaration lines intact) into the calculate function will provide a solution.

/*eslint-env browser*/

var mytotalsq;

function getEconPrice() {
  var EconPrice = 0;
  if (mytotalsq <= 199) {
    return EconPrice.value = .40;
  }
  if (mytotalsq >= 200 && mytotalsq <= 299) {
    return EconPrice.value = .22;
  }
  return EconPrice;
}


function getStickerPrice() {
  var StickerPrice = 0;
  var theForm = document.forms["stickerform"];
  var selectedVinyl = theForm.elements["vinyl"];
  StickerPrice = vinyl_prices[selectedVinyl.value];
  return StickerPrice;
}

function getLaminatePrice() {
  var LaminatePrice = 0;
  var theForm = document.forms["stickerform"];
  var selectedLaminate = theForm.elements["laminate"];
  LaminatePrice = laminate_prices[selectedLaminate.value];
  return LaminatePrice;
}

var vinyl_prices = new Array();
var laminate_prices = new Array();

function calculateTotal() {


vinyl_prices["None"] = 0;
vinyl_prices["Econ"] = getEconPrice();
vinyl_prices["Inter"] = .25;
vinyl_prices["HPerf"] = .35;
vinyl_prices["HiTack"] = .75;
vinyl_prices["Ref"] = .75;


laminate_prices["None"] = 1;
laminate_prices["NoLam"] = 1;
laminate_prices["StanLam"] = 1.43;
laminate_prices["HPLam"] = 1.7;

  var myheight = document.getElementById('height').value;
  var mywidth = document.getElementById('width').value;
  var myquan = document.getElementById('quan').value;
  var totalsq = document.getElementById('totalsq');
  mytotalsq = mywidth * myheight * myquan;
  totalsq.value = mytotalsq;
  var stickerPrice = mytotalsq * getStickerPrice() * getLaminatePrice();
  var divobj = document.getElementById('totalPrice');
  divobj.style.display = 'block';
  divobj.innerHTML = "Total $" + stickerPrice;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <title>RMSticker Pricing</title>
  <script type="text/javascript" src="js/stickercalc.js"></script>
  <link href="css/sticker.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <div id="wrap">
    <form action="" id="stickerform" onsubmit="return false;">
      <div>
        <div class="cont_order">
          <fieldset>
            <legend>RMSticker</legend>
            <label>Height</label>
            <input id="height" type="text" />
            <label>Width</label>
            <input id="width" type="text" />
            <label>Quantity</label>
            <input id="quan" type="text" oninput="calculateTotal()" />
            <input id="totalsq" name="totalsq" type="text" />
            <br/><br/>

            <label>Vinyl</label>

            <select id="vinyl" name='vinyl' onchange="calculateTotal()">
              <option value="None">Select Vinyl</option>
              <option value="Econ">Economy</option>
              <option value="Inter">Intermediate</option>
              <option value="HPerf">High Performance</option>
              <option value="HiTack">High Tack</option>
              <option value="Ref">Reflective</option>
            </select>
            <br/><br/>


            <label>Laminate</label>

            <select id="laminate" name='laminate' onchange="calculateTotal()">
              <option value="None">Select Laminate</option>
              <option value="NoLam">None</option>
              <option value="StanLam">Standard</option>
              <option value="HPLam">High Performance</option>
            </select>

            <br/><br/>

            <label>Select Finish</label>
            <label class='radiolabel'><input type="radio"  name="selectedfinish" value="Matte" onclick="calculateTotal()" />Matte</label><br/>
            <label class='radiolabel'><input type="radio"  name="selectedfinish" value="Satin" onclick="calculateTotal()" />Satin(Only available on laminated stickers)</label><br/>
            <label class='radiolabel'><input type="radio"  name="selectedfinish" value="Gloss" onclick="calculateTotal()" />Gloss</label><br/>



            <div id="totalPrice"></div>

          </fieldset>
        </div>

                       
      </div>
    </form>
  </div>
  <!--End of wrap-->

</body>

</html>

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

What is the best way to manage horizontal scrolling using buttons?

I was hoping that when the button is clicked, the scroll would move in the direction of the click while holding down the button. Initially, it worked flawlessly, but suddenly it stopped functioning. export default function initCarousel() { const carous ...

The AJAX call was successful, however, the response did not contain any data

I have a MySQL table where I use a FOR EACH loop to display data on my page. I then make an AJAX request to update the displayed data every time a new row is inserted into the database. Although the AJAX request is successful, it returns empty data. I&apo ...

What is the importance of maintaining immutability for objects in Redux?

What is the importance of immutability in Redux? While I understand that frameworks like Angular2 use onPush to leverage immutability for quicker rendering of views, I'm interested in learning about other reasons why Redux emphasizes immutability desp ...

The $scope variable does not sync with the express API

I have noticed that the static part of my app is loading fine. Recently, I integrated a service using Express as a simple API. However, when I attempt to set the #scope from my module's controller, it seems like it hasn't loaded at all. I am puzz ...

Performing AJAX callback function on success in jQuery

I've been trying to troubleshoot an error but none of the solutions I've found so far seem to be working for me. I have an ajax request set up to retrieve JSON data from the server. I can see the JSON data that I want to capture when using consol ...

Updates to object properties are not appearing in Vue component

I am facing an issue with a Vue component that has a single prop, which is an object. Despite changing a property in this object, it does not reflect the update in the Vue template. Below is a simplified version of the component: <template> <p ...

Can someone please explain how to prevent Prettier from automatically inserting a new line at the end of my JavaScript file in VS Code?

After installing Prettier and configuring it to format on save, I encountered an issue while running Firebase deploy: 172:6 error Newline not allowed at end of file eol-last I noticed that Prettier is adding a new line at the end when formatting ...

Exploring the process of performing an AJAX JQuery HTTP request using JavaScript and PHP on the server side - any tips?

Greetings! I have developed a web application using HTML, CSS, and JavaScript. To enhance functionality, I have integrated Bootstrap and jQuery into the project. The application comprises both client-side and server-side components. Let's take a look ...

Unlock the Power of Rendering MUI Components in ReactJS Using a For Loop

Hey there! Hope everything is going well. I've been working on a fun project creating an Advent/Chocolate Box Calendar using ReactJS. One challenge I'm facing is figuring out how to iterate over a for loop for each day in December and render it ...

Executing Datalist's Delete Command through Page Methods Implementation

Recently, I came across an issue with my DataList and Update Panel on my webpage. I noticed a significant delay in response time after incorporating the Update panels... intrigued, I delved deeper into this phenomenon and found some interesting insights in ...

Cloud Firestore trigger fails to activate Cloud function

I am facing an issue with triggering a Cloud Function using the Cloud Firestore trigger. The function is supposed to perform a full export of my sub collection 'reviews' every time a new document is added to it. Despite deploying the function suc ...

The provisional headers provided by the local passport authentication strategy offer an added layer

When I send a POST request from my frontend with a username and password object, here is the code: const login = data => ( axios.post('http://localhost:3000/v1/user/login', data) .then(response => response.data) .catch((err) => ...

Tips for utilizing pre-installed validation regulations in VeeValidate 4?

Currently transitioning from Vue 2 to Vue 3, I am interested in utilizing VeeValidate 4 for my validations. However, it seems that the documentation does not provide any information on using built-in rules such as min, max, alpha_spaces, etc. Do I need to ...

How to display an object in JS format using React?

Currently, I am tackling a project that presents me with the following situation: myjson: { completeName: "my name is {this.state.myName+ " "+this.state.surname}" } component.js var Component = React.createClass({ getInitialState: function() { ...

The validation feature in ASP.NET MVC does not seem to be functioning properly while using

I'm struggling to make the bootstrap modal and asp.net mvc validation work together seamlessly. My form is quite complex with validation displayed in a bootstrap modal. However, when I press the submit button, the validation doesn't seem to be fu ...

Notifying asynchronous completion using Gulp, Babel, and configuration file config.yml

My current project involves using babel and gulp for handling tasks, as well as loading a yml config file for paths. This is the content of cofing.yml: PATHS: # Path to source folder sources: "jet/static/jet_src" # Path to dist folder dist: "jet/ ...

Using the ES6 filter method to iterate through a double nested array of objects

Struggling with filtering a nested array of objects and specifically stuck at the filter part. Any idea on how to eliminate one of the marks? this.state = { data: [ { id: 1, name: "Main", subs: [ { id: "jay", ...

Angular ERROR: Trying to access rating property of an undefined value

I'm encountering an issue on a website where users can vote for their favorite animal. Whenever I try to select an animal to vote for, I receive an unclear error message that has been difficult to resolve even after searching online for a solution. A ...

Reading an XML file to locate items nested within the same bracket

Within my JavaScript function, I am utilizing the following code to extract data from an XML file: var title = $(this).children('Title').text(); This snippet of code successfully retrieves the content under the <Title> tags: <Title> ...

Is there a way to mount or unmount a React component by pressing a single key?

I am currently developing an application that showcases 3D objects upon pressing certain keys on the keyboard. My goal is to have these objects disappear after 2-3 seconds or once the animation completes. Below is the component responsible for managing th ...