locked
adding numbers in javascript or using textchanged and create postback RRS feed

  • Question

  • User-1767698477 posted

    I have a large page. It is over 5000 lines of code! It's a form with lots of of textboxes, dropdowns, and checkboxes. When numbers are entered into certain boxes, calculations are to be performed. It requires 2 or 3 numbers for the calc to work. I'm not getting the result in the code below currently. I wish I could use breakpoints in the javascript like I do in vb.net. Is it possible to see this in vs for the javascript?

    Is it better to just use javascript and not create a postback?  I have read that I can use ontextchanged method to change a value in a textbox.

    I wrote the following code but it is not working. Can someone possibly explain the problem?

    <script type="text/javascript">
            function isEmpty(val) {
                return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
            }
        </script>
        <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script type="text/javascript">
            function math1() {
                var txtloanamt = document.getElementById('txtloanamount').value
                var txtpercent = document.getElementById('txtdiscountpercentage').value;
                var txtaddlamt = document.getElementById('txtdiscountaddlamt').value;
                if (txtLoanamt.length > 0 ) {
                    if ((txtpercent.length > 0 ) && (txtaddlamt.length >  0)) {
                        var result = parseInt(txtloanamt) * parseInt(txtpercent) + parseint(txtaddlamt);
                    } else if ((txtpercent.length>0) && (txtaddlamt.length ==0)) {
                        var result = parseInt(txtloanamt) * parseInt(txtpercent);
                    } else if ((txtpercent.length ==0) && (txtpercent.length > 0)) {
                        var result = parseInt(txtaddlamt);
                        if (!isNaN(result)) {
                            document.getElementById('txtdiscounttotal').value = result;
                        }
                    }
        </script>
    
    
    
      <td>
                    <asp:TextBox ID="txtdiscountpercentage" runat="server" Width="50" onkeyup="math1()"></asp:TextBox>% + $
                    <asp:TextBox ID="txtdiscountaddlamt" runat="server" Width="75" onkeyup="math1()"></asp:TextBox>
                </td>
                <td>$<asp:TextBox ID="txtdiscounttotal" runat="server" Width="90"></asp:TextBox>
                </td>

    Sunday, July 19, 2020 12:15 AM

Answers

  • User303363814 posted

    The code sample I provided was intended to be used!

    document is an object

    getElementById is a method.

    The method whose name is getElementById takes a single parameter.

    That parameter is placed between opening and closing parenthesis

    The parameter for the method getELementById is a string.

    In this case you are providing a literal string.

    A literal string is placed between quotation marks (either single or double)

    This thing ---------|
                        |
                        V
    getElementById(     '    <%=txtloanamount.ClientID%>   '   )
                                                           ^
                                                           |
                                  and this thing ----------|                                  

    I can't think how to be any plainer.  Maybe, someone else can help???

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, July 25, 2020 10:40 AM

All replies

  • User303363814 posted

    Can you add some detail to

    it is not working.

    Wrong answer (what do you expect, what do you get, with what inputs)?

    no answer (with what inputs)?

    error (give details)?

    It really helps

    There are some obvious things wrong

    else if ((txtpercent.length ==0) && (txtpercent.length > 0)) {

    The length cannot be both 0 and greater than 0!

    You declare (and set) a variable called 'result' several times inside different blocks - so you will have several variables. Probably not what you want

    The final else branch, which can never execute (see first problem) is the only place that attempts to change txtdiscounttotal.  Is this what you want?

    Sunday, July 19, 2020 2:25 AM
  • User-474980206 posted

    The browsers all have good JavaScript debuggers. But in JavaScript just  like c#, variables are case sensitive. You set

    txtloanamt

    but use

    txtLoanamt

    the browser should show undefined error.

    Sunday, July 19, 2020 4:05 PM
  • User-1767698477 posted
    ok, I cleaned that up, but it still doesn't work. I will just have to debug in browser. 

    <script type="text/javascript"> function math1() { var txtloanamt = document.getElementById('txtloanamount').value var txtpercent = document.getElementById('txtdiscountpercentage').value; var txtaddlamt = document.getElementById('txtdiscountaddlamt').value; if (txtloanamt.length > 0) { if ((txtpercent.length > 0) && (txtaddlamt.length > 0)) { var result = parseInt(txtloanamt) * parseInt(txtpercent) + parseint(txtaddlamt); } else if ((txtpercent.length > 0) && (txtaddlamt.length == 0)) { var result = parseInt(txtloanamt) * parseInt(txtpercent); } else if ((txtpercent.length == 0) && (txtaddlamt.length > 0)) { var result = parseInt(txtaddlamt); if (!isNaN(result)) { document.getElementById('txtdiscounttotal').value = result; } } </script>

    Sunday, July 19, 2020 10:35 PM
  • User-1330468790 posted

    Hi sking,

     

    One useful debugging method is setting console.log() in the key path of the function execution.

     

    I just test your codes and find some errors in the js code which might cause the silence of the function.

    • parseint is not a function, instead, change to parseInt as others.
    • document.getElementById('txtdiscounttotal').value = result; only works when the percent input is nothing and addlamt input's length is larger than 0. However, you might need to move this statement out of IF block.

    The code should as below (TextBox "txtloanamount" is added by myself): 

     <asp:TextBox ID="txtloanamount" runat="server" Width="50" onkeyup="math1()"/>
             <asp:TextBox ID="txtdiscountpercentage" runat="server" Width="50" onkeyup="math1()"></asp:TextBox>% + $
             <asp:TextBox ID="txtdiscountaddlamt" runat="server" Width="75" onkeyup="math1()"></asp:TextBox>
               
                $<asp:TextBox ID="txtdiscounttotal" runat="server" Width="90"></asp:TextBox>
    
                 
    
            <script>
                function isEmpty(val) {
                    return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
                }
                function math1() {
                    console.log("Start the math1 function");
                    var txtloanamt = document.getElementById('txtloanamount').value
                    console.log("txtloanamt: " + txtloanamt);
                    var txtpercent = document.getElementById('txtdiscountpercentage').value;
                    console.log("txtpercent: " + txtpercent);
                    var txtaddlamt = document.getElementById('txtdiscountaddlamt').value;
                    console.log("txtaddlamt: " + txtaddlamt);
                    if (txtloanamt.length > 0) {
                        console.log("Length > 0");
                        if ((txtpercent.length > 0) && (txtaddlamt.length > 0)) {
                            console.log("txtpercent.length > 0 && txtaddlamt.length > 0");
                            var result = parseInt(txtloanamt) * parseInt(txtpercent) + parseInt(txtaddlamt);
                            console.log("result1: " + result);
                        } else if ((txtpercent.length > 0) && (txtaddlamt.length == 0)) {
                            console.log("txtpercent.length > 0 && txtaddlamt.length == 0");
                            var result = parseInt(txtloanamt) * parseInt(txtpercent);
                            console.log("result2: " + result);
                        } else if ((txtpercent.length == 0) && (txtpercent.length > 0)) {
                            console.log("txtpercent.length == 0 && txtpercent.length > 0");
                            var result = parseInt(txtaddlamt);
                            console.log("result3: " + result);
                            
                        }
    // This should be executed after IF block if (!isNaN(result)) { document.getElementById('txtdiscounttotal').value = result; console.log("Final Result: " + result); } } } </script>

    Result: I don't know the correct layout so that you have to check the layout according to above html markup.

     

    BTW, I provide the console.log() functions in the code for debugging. You could check the console information in dev-tool (press F12 in browser and click the console tab).

     

    Hope this can help you.

    Best regards,

    Sean

    Monday, July 20, 2020 6:14 AM
  • User303363814 posted

    it still doesn't work.

      ???????

    If all three variables txt* have length greater than 0 you compute a variable called result, then it goes out of scope and then you exit the function.  That is you do **precisely** nothing.  No changes to anything happens.  Is this what you want?

    If loanamt.length > 0 and addlamt.length is zero, then you do the same precisely nothing.  You still haven't said what you want to happen but you seem to do a lot of work to achieve nothing.

    Finally, if loanamtlength > 0 and percent.length is zero you do something.  You compute result again, but this time you actually use it!  If it is a number then it is made to be the value of some other control.

    Bottom line - sometimes your code copies txtaddlamt to txtdiscounttotal.  In most cases it does nothing.  

    Monday, July 20, 2020 7:31 AM
  • User-1767698477 posted

    I have checked the code and it is as exactly as you have shown it here. I created a separate page with it also. The separate page I made does work.  So something is preventing it form working in the page on my site. The page on my site is 5504 lines, but there is no other javascript on the page. So what could be causing the issue? I have a tooltip script in the master page. I tried deleting the tooltip script out of the master page and this did not help. So if must be something else.

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
    <link href="http://fonts.googleapis.com/css?family=Raleway:400,200,500,600,700,800,300"
    rel="stylesheet" />
    <link href="default.css" rel="stylesheet" type="text/css" media="all" />
    <link href="fonts.css" rel="stylesheet" type="text/css" media="all" />
    <!--[if IE 6]>
    <link href="default_ie6.css" rel="stylesheet" type="text/css" />
    <![endif]-->
    </head>
    <body>
    <form id="Form1" runat="server">
    <script type="text/javascript" src="wz_tooltip.js"></script>

    Tuesday, July 21, 2020 5:41 AM
  • User-1767698477 posted

    I have uploaded the test page and the main page into my site. The test page works correctly, but the same exact code is not working on the main page.  I show undefined in the javascript debugger.  To see this, you can login here at http://www.mortgageloanapply.com as johndoe and the pw is Johndoe1@

    Just click on the button that says fees and you will see the link at the top for the test page.  The first disabled text box should be displaying the contents of the loan amount times the percent plus the additional amount.

    Thursday, July 23, 2020 5:39 PM
  • User303363814 posted

    It is easier to help you with what is wrong if you take us through the steps of what does not work.  The example page you lead us to seems to work - very hard to fix it if it works!

    Still guessing because you refuse to show what is wrong or what you want to happen but I will apply basic debugging techniques

    1. Locate the first error
    2. Fix it
    3. Go to step 1.

    You have sprinkled 'console.log' through your javascript.  Have you read the console messages that you create?  When I type the first character in the input box which has a label of 'Loan Amount' my console looks like

    Start the math1 function
    fees.aspx:15 Uncaught TypeError: Cannot read property 'value' of null
        at math1 (fees.aspx:15)
        at HTMLInputElement.onkeyup (fees.aspx:174)

    Immediately after the statement which displays "Start the math1 function' comes the statement 

    var txtloanamt = document.getElementById('txtloanamount').value;

    Notice that this uses the property 'value' and that the error message tells us that "Cannot read property 'value' of null".  Hmmm, maybe document.getElementById('txtloanamount') is null?  Assuming nothing, I search for some element with an id of 'txtxloanamount'.  Bingo! There isn't one - that would be why you get a null.  The input box with the label 'Loan Amount' looks like this

    <input name="ctl00$ContentPlaceHolder2$txtloanamount" type="text" value="250000" id="ContentPlaceHolder2_txtloanamount" onkeyup="math1()" style="width:100px;">

    Rick Strahl https://weblog.west-wind.com/posts/2009/nov/07/clientidmode-in-aspnet-40 gives a good overview of this problem and ways to fix it. (he also mentions, at the top, the old way of using .ClientID but one of the V4 methods would be cleaner)

    That should help you with "Step 2" in my universal debugging methodology™.  Now move to "Step 3".

    You still have multiple variables called 'result' declared.  My knowledge of javascript is not good enough to know how all browsers will treat the declaration and initialisation of the same local variable.  I would suggest that you avoid doing that unless you really know what you are doing.

    Thursday, July 23, 2020 11:37 PM
  • User-1767698477 posted

    Hi PaulTheSmith,

    Thanks for the info. As soon as I read the article, a light blub went on in my brain. You see the memoires of this chapter are long past but still reside in my brain cells....

    Ok, right, asp slaps on the good ol ct100 to the variables.

    So I modified it, and I see my default value sitting there in the loanamount textbox, but the variable still says undefined when I hover my mouse over it. Here's the code and a snapshot.

    <script type="text/javascript">
            function isEmpty(val) {
                return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
            }
            function math1() {
                console.log("Start the math1 function");
                var txtloanamt = document.getElementById(<%=txtloanamount.ClientID%>).value
                console.log("txtloanamt: " + txtloanamt);
                alert("Value of loan is " + txtloanamt);
                var txtpercent = document.getElementById(<%=txtdiscountpercentage.ClientID%>).value;
                console.log("txtpercent: " + txtpercent);
                var txtaddlamt = document.getElementById(<%=txtdiscountaddlamt.ClientID%>).value;
                console.log("txtaddlamt: " + txtaddlamt);
                if (txtloanamt.length > 0) {
                    console.log("Length > 0");
                    if ((txtpercent.length > 0) && (txtaddlamt.length > 0)) {
                        console.log("txtpercent.length > 0 && txtaddlamt.length > 0");
                        var result = (parseFloat(txtloanamt) * (parseFloat(txtpercent)) / 100) + parseInt(txtaddlamt);
                        console.log("result1: " + result);
                    } else if ((txtpercent.length > 0) && (txtaddlamt.length == 0)) {
                        console.log("txtpercent.length > 0 && txtaddlamt.length == 0");
                        var result = (parseFloat(txtloanamt) * (parseFloat(txtpercent)) / 100);
                        console.log("result2: " + result);
                    } else if ((txtpercent.length == 0) && (txtaddlamt.length > 0)) {
                        console.log("txtpercent.length == 0 && txtaddlamt.length > 0");
                        var result = parseFloat(txtaddlamt);
                        console.log("result3: " + result);
    
                    }
                    // This should be executed after IF block
                    if (!isNaN(result)) {
                        document.getElementById('txtdiscounttotal').value = result;
                        console.log("Final Result: " + result);
                    }
                }
            }
        </script>

    Friday, July 24, 2020 8:55 PM
  • User303363814 posted

    The parameter of getElementById is a string

    getElementById('<%=txtloanamount.ClientID%>')

    Friday, July 24, 2020 10:28 PM
  • User-1767698477 posted

    It seems that there should be a number in this variable txtloanamount when I hover my mouse over it. It would be a string.

    var txtloanamt = document.getElementById(<%=txtloanamount.ClientID%>).value;

    Here is what is displayed form the view source: 

    <input name="ctl00$ContentPlaceHolder2$txtloanamount" type="text" value="250000" maxlength="8" id="ctl00_ContentPlaceHolder2_txtloanamount" onkeyup="math1()" style="width:100px;" />

    Down below, I'm checking the length and then using parseFloat to turn it into a number which can be added. The logic is all correct. So it should just be a matter of getting past this ct100 issue. Where is the number which is input to the text boxes for loanamt, percent and the addlamt?  Why isn't it appearing in the variables as strings?

    <script type="text/javascript">
            function isEmpty(val) {
                return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
            }
            function math1() {
                console.log("Start the math1 function");
                var txtloanamt = parseFloat(document.getElementById(<%=txtloanamount.ClientID%>).value);
                console.log("txtloanamt: " + txtloanamt);
                alert("Value of loan is " + txtloanamt);
                var txtpercent = parseFloat(document.getElementById(<%=txtdiscountpercentage.ClientID%>).value);
                console.log("txtpercent: " + txtpercent);
                var txtaddlamt = parseFloat(document.getElementById(<%=txtdiscountaddlamt.ClientID%>).value);
                console.log("txtaddlamt: " + txtaddlamt);
                if (txtloanamt.length > 0) {
                    console.log("Length > 0");
                    if ((txtpercent.length > 0) && (txtaddlamt.length > 0)) {
                        console.log("txtpercent.length > 0 && txtaddlamt.length > 0");
                        var result = (txtloanamt * txtpercent / 100) + parseInt(txtaddlamt);
                        console.log("result1: " + result);
                    } else if ((txtpercent.length > 0) && (txtaddlamt.length == 0)) {
                        console.log("txtpercent.length > 0 && txtaddlamt.length == 0");
                        var result = (txtloanamt * txtpercent / 100);
                        console.log("result2: " + result);
                    } else if ((txtpercent.length == 0) && (txtaddlamt.length > 0)) {
                        console.log("txtpercent.length == 0 && txtaddlamt.length > 0");
                        var result = txtaddlamt;
                        console.log("result3: " + result);
    
                    }
                    // This should be executed after IF block
                    if (!isNaN(result)) {
                        document.getElementById('txtdiscounttotal').value = result;
                        console.log("Final Result: " + result);
                    }
                }
            }
        </script>

    1. <div style="display: flex;"> <div style="white-space: pre-wrap;">SCRIPT5007: SCRIPT5007: Unable to get property 'value' of undefined or null reference</div> </div> fees.aspx (15,13)
    Saturday, July 25, 2020 4:07 AM
  • User303363814 posted

    The code sample I provided was intended to be used!

    document is an object

    getElementById is a method.

    The method whose name is getElementById takes a single parameter.

    That parameter is placed between opening and closing parenthesis

    The parameter for the method getELementById is a string.

    In this case you are providing a literal string.

    A literal string is placed between quotation marks (either single or double)

    This thing ---------|
                        |
                        V
    getElementById(     '    <%=txtloanamount.ClientID%>   '   )
                                                           ^
                                                           |
                                  and this thing ----------|                                  

    I can't think how to be any plainer.  Maybe, someone else can help???

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, July 25, 2020 10:40 AM
  • User-1767698477 posted

    Okay...I have studied this. If you look at my original code, I had it

      var txtloanamt = parseFloat(document.getElementById('txtloanamount').value);

    Then I changed it to :
    var txtloanamt = parseFloat(document.getElementById(<%=txtloanamount.ClientID%>).value);

    I figured out last night by watching some youtube videos and other documents that the quotes were missing. So I added
    them and now this below is working:

    var txtloanamt = document.getElementById('<%=txtloanamount.ClientID%>').value

    Interestingly, either a single quote or a double quote will work. '<% %>' "<% %>"

    I originally added a master page to the smaller page default2 and then transferred my code to the larger page.
    Now the problem is that when the page loads, it populates numbers from the database into the fields, but the javascript
    calculation for the result box doesn't get fired on page load. It only works when you change the numbers in the text box.
    So how do I get it to fire on page load after the numbers are populated?

    I figured this out also, and I'm adding to the <body onload="math1();credit1()"> in my master page. This working for me.
    There will be about 50 javascript functions for the page, and the page is 5500 lines now. It will be well over 6k lines.
    Would it be better to use a separate javascript file outside the page? If so, will that change the coding?


    Saturday, July 25, 2020 5:18 PM
  • User303363814 posted

    If both single and double quotes working is a surprise to you then I suggest that you try a Javascript tutorial.  Maybe https://www.w3schools.com/js/ is a good starting place?  Instead of fighting fires with each problem as it comes up you will save a lot of time but spending a few hours to get the basics solidly understood

    Sunday, July 26, 2020 12:25 AM