Web Analytics Made Easy -
StatCounter JS beginner: isNaN alert error message - CodingForum

Announcement

Collapse
No announcement yet.

JS beginner: isNaN alert error message

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • JS beginner: isNaN alert error message

    hi - i'm working on an assignment for a class, and i can't figure out why my isNaN alert/"Must be a valid number" error pops up no matter what I enter. this is a step up from nothing happening at all when i click calculate, but any help is appreciated.

    thanks!

    Code:
    "use strict";
    var $ = function (id) {
        return document.getElementById(id);
    };
    					
    	
    function processEntry (income = document.getElementById("income").value) {
    		 income = parseFloat (income);
    		 if (isNaN(income)) {
            alert ("Must be a valid number.");
    	    }
    	    else {
            $("tax").value=calculateTax(income);
                }
            }
    
    
     var calculateTax = function (income) {
      
       var tax = 0;
       	if (income > 0 && income <= 9225){
    		tax = (income * 0.10);
    	}
    	
    	else if (income <= 37450 && income > 9225) {
    		tax = (income - 37450) * 0.15 + 922.50;
    	}
    		
    	else if (income <= 90750 && income > 37450) {
    		tax = (income - 90750) * 0.25 + 5156.25;
    	}
    		
    	else {
    		tax = income * 0.10;
    	}
    
    var resultTax = calculateTax(income);
    	$("tax").value = tax;
    	
    	tax = resultTax.toFixed(2);
    	return tax;	
    	}
    
    window.onload = function () {
        $("calculate").onclick = processEntry;
    };
    Last edited by vinyl-junkie; Sep 10, 2016, 09:44 AM. Reason: added code tags

  • #2
    Try moving the assignment on the processEntry to after the {

    Code:
    function processEntry () {
    income = document.getElementById("income").value;
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

    Comment


    • #3
      When i do that, i go back to nothing happening when i click calculate, which probably means i have an error somewhere else?

      --
      Code:
      "use strict";
      var $ = function (id) {
          return document.getElementById(id);
      };
      					
      	
      function processEntry () {
      	income = document.getElementById("income").value;
      		 income = parseFloat (income);
      		 if (isNaN(income)) {
              alert ("Must be a valid number.");
      	    }
      	    else {
              $("tax").value=calculateTax(income);
                  }
              }
      
      
       var calculateTax = function (income) {
        
         var tax = 0;
         	if (income > 0 && income <= 9225){
      		tax = (income * 0.10);
      	}
      	
      	else if (income <= 37450 && income > 9225) {
      		tax = (income - 37450) * 0.15 + 922.50;
      	}
      		
      	else if (income <= 90750 && income > 37450) {
      		tax = (income - 90750) * 0.25 + 5156.25;
      	}
      		
      	else {
      		tax = income * 0.10;
      	}
      
      var resultTax = calculateTax(income);
      	$("tax").value = tax;
      	
      	tax = resultTax.toFixed(2);
      	return tax;	
      	
      	}
      
      window.onload = function () {
          $("calculate").onclick = processEntry;
      };
      Last edited by vinyl-junkie; Sep 10, 2016, 09:44 AM. Reason: added code tags

      Comment


      • #4
        So what error message are you getting in the console?
        Stephen
        Learn Modern JavaScript - http://javascriptexample.net/
        Helping others to solve their computer problem at http://www.felgall.com/

        Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

        Comment


        • #5
          what is the error.. tell in details

          Comment


          • #6
            Originally posted by felgall View Post
            So what error message are you getting in the console?
            That's the thing I really don't understand - I don't get any errors in the console, and the debugger I found that's been pretty helpful so far says that my code is correct. When I've had error messages, I've had a place to start looking for mistakes, but this time I'm at a loss. There's supposedly no errors but program won't run.

            Comment


            • #7
              What does the HTML look like?
              Stephen
              Learn Modern JavaScript - http://javascriptexample.net/
              Helping others to solve their computer problem at http://www.felgall.com/

              Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

              Comment


              • #8
                Originally posted by felgall View Post
                What does the HTML look like?
                Code:
                <!DOCTYPE html>
                <html>
                <head>
                	<meta charset="utf-8">
                	<title>Income Tax Calculator</title>
                   	<link rel="stylesheet" href="styles.css">
                    <script src="calculate_tax_Dennis.js"></script>
                </head>
                
                <body>
                <main>
                    <h1>Income Tax Calculator</h1>
                
                    <label>Enter taxable income:</label>
                    <input type="text" id="income" />
                    <input type="button" value="Calculate" name="calculate" id="calculate" /><br><br>
                
                    <label>Income tax owed:</label>
                    <input type="text" id="tax"><br>
                
                </main>
                </body>
                </html>
                Last edited by vinyl-junkie; Sep 10, 2016, 09:43 AM. Reason: added code tags

                Comment


                • #9
                  Originally posted by felgall View Post
                  So what error message are you getting in the console?
                  I rearranged some things and now it's giving me an error! (Oddly excited about this) Error: Uncaught ReferenceError: income is not defined

                  --

                  code:

                  Code:
                  "use strict";
                  var $ = function (id) {
                      return document.getElementById(id);
                  };
                  	
                  function processEntry () {
                  	income = document.getElementById("income").value;
                  	 if (isNaN(income)) {
                          alert ("Must be a valid number.");
                  	    }
                  	    else {
                          $("tax").value=calculateTax(income);
                              }
                          }
                  var resultTax = calculateTax(income);
                  	$("tax").value = tax;
                      $("income").value = income;
                  	 income = parseFloat (income);
                  
                   function calculateTax(income) {
                    
                     var tax = 0;
                     	if (income > 0 && income <= 9225){
                  		tax = (income * 0.10);
                  	}
                  	
                  	else if (income <= 37450 && income > 9225) {
                  		tax = (income) * 0.15 + 922.50;
                  	}
                  		
                  	else if (income <= 90750 && income > 37450) {
                  		tax = (income) * 0.25 + 5156.25;
                  	}
                  		
                  	else {
                  		tax = income * 0.10;
                  	}
                  
                  	tax = resultTax.toFixed(2);
                  	return tax;	
                  	}
                  
                  window.onload = function () {
                      $("calculate").onclick = processEntry;
                  };
                  Last edited by vinyl-junkie; Sep 10, 2016, 09:42 AM. Reason: added code tags

                  Comment


                  • #10
                    income = document.getElementById("income").value;

                    Because you have not used var the variable income is global. And you are assigning the same name to an HTML element and a Javascript variable, which is bad practice, as well as maybe causing a conflict here.

                    All the code given in this post has been tested and is intended to address the question asked.
                    Unless stated otherwise it is not just a demonstration.

                    Comment


                    • #11
                      First off, lose the silly $ nonsense, getElementById isnt' THAT hard... but it is a SLOW operation, so I would get those elements ahead of time at load. To that end I would put the whole thing in a self-instancing function to give it isolated variable scope, and then load it before </body> instead of inside <head>

                      Scripting inside <head> can block the page load, take longer to load, and they will often run before rendering of the page is even complete -- hence the need for the onload. If you move the script to before </body> you don't need to onload as the DOM will be populated by then...

                      You also have a bit of a logic disconnect in your gaggle of pointless IF statements. When you already know that the value isn't another condition, you don't need to test it again. You already KNOW it's <= 9225, you don't need to test for > 9225! Etc, etc...

                      so... for your markup, move the script to the end:
                      Code:
                      <!DOCTYPE html><html lang="en"><head><meta charset="utf-8">
                      <link rel="stylesheet" href="styles.css" media="screen,projection,tv">
                      <title>Income Tax Calculator</title>
                      </head><body>
                      
                      <h1>Income Tax Calculator</h1>
                      
                      <label for="calculate">Enter taxable income:</label>
                      <input type="text" id="income" />
                      <input type="button" value="Calculate" name="calculate" id="calculate" /><br>
                      <br>
                      <label for="tax">Income tax owed:</label>
                      <input type="text" id="tax" disabled><br>
                      
                      <script src="calculate_tax_Dennis.js"></script>
                      
                      </body></html>
                      Losing the pointless "main" tag since you don't even have enough markup yet to say that, and "main" is pretty pointless if you just leverage numbered headings and horizontal rules properly. Same goes for section, article, nav, aside, and all the other garbage HTML 5 tags that serve zero legitimate purpose given not one legitimate user-agent has done anything with them but treat them all like glorified DIV... and don't forget your FOR attributes!

                      Of course written properly that would be a full form with a fieldset, and a proper submit as a scripting off fallback, that way if scripting is blocked or otherwise unavailable, you aren't pissing off the users! In that case you'd be catching onsubmit on the form and cancelling the event, not trapping click on a button.

                      Then for your script:
                      Code:
                      "use strict";
                      (function(d) {
                      
                      	var
                      		income = d.getElementById('income'),
                      		tax = d.getElementById('tax');
                      
                      	function processEntry () {
                      		if (isNaN(income.value)) alert('Must be a valid number.');
                      		else tax.value = calculateTax(income.value).toFixed(2);
                      	}
                      
                      	function calculateTax(amt) {
                      		if (amt <= 9225) {
                      			if (amt <= 37450) return (amt - 37450) * 0.15 + 922.50;
                      			if (amt <= 90750) return (amt - 90750) * 0.25 + 5156.25;
                      		}
                      		return amt * 0.10; // you SURE that's right?!? also catches OVER 90k!
                      	}
                      
                      	d.getElementById('calculate').addEventListener('click', processEntry, false);
                      
                      })(document);
                      The wrapping function isolates our functions and variables in scope. By passing document as d we don't have to say document every Joe blasted time (runs faster too, locals are higher up in the lookup order), we can just make them normal functions instead of dicking around making them variables, the calculate function is GREATLY simplified with the return short-circuiting out so unused code isn't even run, by using addEventListener we open the door to other scripts hooking the event if need be reducing the odds of conflicts, etc, etc, etc...

                      Actually, the math in your original makes no sense whatsoever... what are the applicable margins being applied here as nothing in this thread in that regard makes a lick of sense. I wouldn't think you'd be subtracting 37450 if the amount is less than or equal to that!!! On the high end it's even worse -- you're either missing a bracket, or applying them wrong.
                      Last edited by deathshadow; Sep 10, 2016, 05:12 AM.
                      Walk the dark path, sleep with angels, call the past for help.
                      https://cutcodedown.com
                      https://medium.com/@deathshadow

                      Comment


                      • #12
                        I caught my math errors late last night, you're definitely right that my original made no sense whatsoever hahaha

                        As for the rest, THANK YOU!!! You've all given me more "why" and practical knowledge in this thread than my instructor has in the three weeks of the class. Her answer for every question has been to go check the textbook, or to check solution code when we have it available. I keep saying that this isn't teaching us best practices, it's just teaching us to cobble something together until it (might) work. It's been a really frustrating class when I don't just want to learn to copy and paste stuff, I want to learn how to do it right myself.

                        Comment


                        • #13
                          Originally posted by blondiejess88 View Post
                          I caught my math errors late last night, you're definitely right that my original made no sense whatsoever hahaha

                          As for the rest, THANK YOU!!! You've all given me more "why" and practical knowledge in this thread than my instructor has in the three weeks of the class. Her answer for every question has been to go check the textbook, or to check solution code when we have it available. I keep saying that this isn't teaching us best practices, it's just teaching us to cobble something together until it (might) work. It's been a really frustrating class when I don't just want to learn to copy and paste stuff, I want to learn how to do it right myself.
                          Sadly many Javascript classes are like this - a case of the blind leading the blind.

                          All the code given in this post has been tested and is intended to address the question asked.
                          Unless stated otherwise it is not just a demonstration.

                          Comment

                          Working...
                          X