Unexplained parseInt() behavior

By | July 12, 2018

I’m beginning to teach myself JavaScript via HeadFirst JavaScript, and I’ve hit a little bit of a snag. The chapter I’m doing focuses on handling input of data into forms. When I try to use the updateOrder() function, the parseInt() returns NaN, but the alert statements I’ve put in print the correct values. When I substitute “0” for “” in the value parts of the HTML code, I then get the correct behavior. This leads me to believe that a null character is being prepended to the input.

Update: It’s late, and I should know better than to be typing code right now. I believe I have fixed all of the typos, and the code is as I have it in my sandbox run. I also want to than @imEnCoded for the edit contribution. Now that the typos are fixed, the original problem I posted about should present correctly.

My questions are:

  • Am I doing something wrong (Minus some formatting changes, my code
    is exactly as how it is in the book)?

  • Is there any way to get around this? I’ve seen one post on here
    that suggests using regular expressions to filter out any before
    characters, but I was kind of hoping for something cleaner.

For brevity, I’ve only included what I’ve determined to be the troublesome code here, but I will link the full solution code too.

Full HTML and JS for solution is here

The JavaScript part:

function updateOrder(){
    var TAXRATE=0.0925;
    var DONUTPRICE=0.50;
    var numCakeDonuts=parseInt(document.getElementById("cakedonuts")
    var numGlazedDonuts=parseInt(document.getElementById("glazeddonuts")

       //alerts put by me to see what is actually held by variables
       //after parsing
       alert("Number of cake donuts is: "+numCakeDonuts);
       alert("Number of glazed donuts is: "+numGlazedDonuts);

        //...rest of code for function here

and the given HTML that intakes the values is:

 <!--There's some non-troublesome HTML before this section-->
     Number of cake donuts:<input type="text" id="cakedonuts" 
                            name="cakedonuts" value="" 

     Number of glazed donuts:<input type="text" id="glazeddonuts"
     name="glazeddonuts" value="" onchange="updateOrder();"/>
<!--And some after-->

Leave a Reply

Your email address will not be published. Required fields are marked *