Combine Javascript and ASP.Net

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #16
    If you use IE8 it comes with a debugger tool.
    Hit F12.

    If you use FireFox then download something like FireBug (this is what I use).


    -Frinny

    Comment

    • stefbek97
      New Member
      • Aug 2009
      • 54

      #17
      Function

      Just finished the function that Recognizes server controls. So this would work if I had only one set of textboxes to calculate the average.

      Now I need to figure out how to pass a row to Javascript, loop throgh the rows and find the controls then calculate the average. phew...

      Code:
      <script language="javascript" type="text/javascript">
          function CalcAverage() {
              var txtSteps = document.getElementById('<%= txt1.ClientID %>');
              var txtDays = document.getElementById('<%= txt2.ClientID %>');
              var txtAverage = document.getElementById('<%= txt3.ClientID %>');
              var nSteps = 0;
              var nDays = 0;
              var nAverage = 0;
              if (txtSteps.value != '')
                  nSteps = parseInt(txtSteps.value);
              if (txtDays.value != '')
                  nDays = parseInt(txtDays.value);
              if ((nSteps != 0) && (nDays != 0)) {
                  nAverage = (nSteps / nDays);
                  nAverage = Math.round(nAverage);
                  txtAverage.value = nAverage;
              }
              else {
                  txtAverage.value = 0;
              }
      
          }        
              
          }  
      </script>
      C# Code Behind

      Code:
          protected void Page_Load(object sender, EventArgs e)
          {
              txt1.Attributes["OnBlur"] = "CalcAverage()";
              txt2.Attributes["OnBlur"] = "CalcAverage()";
          }

      Comment

      • stefbek97
        New Member
        • Aug 2009
        • 54

        #18
        Javascript Function

        Hello,

        I Am new to javascript. I am trying to create a function like this...
        My main problem are these lines for code

        var variable = "TotalSteps ";
        var element = "'" + '<' + '%' + '= ' + 'txt' + variable + '.ClientID' + ' %' + '>' + "'"
        var txtSteps = document.getEle mentById(elemen t);

        here is the complete Function.

        Code:
        function CalcAverage() {
                var variable = "TotalSteps";
                var element = "'" + '<' + '%' + '= ' + 'txt' + variable + '.ClientID' + ' %' + '>' + "'"
                var txtSteps = document.getElementById(element);
                var txtDays = document.getElementById('<%= txtDaysOfSteps.ClientID %>');
                var txtAverage = document.getElementById('<%= txtAvgSteps.ClientID %>');
                var nSteps = 0;
                var nDays = 0;
                var nAverage = 0;
                if (txtSteps.value != '')
                    nSteps = parseInt(txtSteps.value);
                if (txtDays.value != '')
                    nDays = parseInt(txtDays.value);
                if ((nSteps != 0) && (nDays != 0)) {
                    nAverage = (nSteps / nDays);
                    nAverage = Math.round(nAverage);
                    txtAverage.value = nAverage;
                }
                else {
                    txtAverage.value = 0;
                }
            }

        Comment

        • Dormilich
          Recognized Expert Expert
          • Aug 2008
          • 8694

          #19
          this stuff (<%= … %>) looks like ASP code. before JavaScript executes, all ASP is processed, thus calling <%= … %> in JavaScript does nothing.

          Comment

          • stefbek97
            New Member
            • Aug 2009
            • 54

            #20
            What i am doing is tring to find server side controls. I do not want to hard code the Control names in the function but pass them as parameters and build a Var that will represent '<%= txtControlName. ClientID %>' That way i have a flexible function. All i do is pass the control Name and calculate my averages.

            Comment

            • Dormilich
              Recognized Expert Expert
              • Aug 2008
              • 8694

              #21
              as I said, ASP is done server side, once you’re at the client, ASP tags are mere text.

              Comment

              • stefbek97
                New Member
                • Aug 2009
                • 54

                #22
                Maybe we are not understanding each other. Do you agree that server control attributes and properties can me manipulated within a Javascript function? Also by using document.getEle mentById('<%= ServerControlID .ClientID %>');
                you can access those controls?

                Comment

                • Dormilich
                  Recognized Expert Expert
                  • Aug 2008
                  • 8694

                  #23
                  I’m in no way an ASP expert, all I know is, that any ASP controls created by JavaScript are not executed by ASP. you just can’t do server side code on the client. see also the source code of your document in the browser.

                  Comment

                  • stefbek97
                    New Member
                    • Aug 2009
                    • 54

                    #24
                    Thanks for the reply. I am not expecting you to know ASP.net since I am posting this a javascript question. If anyone that reads this knows ASP.Net and javascript and has run Into this situation please answer.

                    Comment

                    • Frinavale
                      Recognized Expert Expert
                      • Oct 2006
                      • 9749

                      #25
                      Stefbek97, please do not double post your question. It divides our attempts to help you, thus making it hard for us to see what other experts have already advised and it makes it difficult for you to get an answer to your question.

                      I've merged your double posts together.

                      Comment

                      • Frinavale
                        Recognized Expert Expert
                        • Oct 2006
                        • 9749

                        #26
                        In post #4 I posted the following:
                        Originally posted by Frinavale
                        ...Notice how I used the <%= %> syntax. This is ASP shorthand for calling the Response.Write( ) method. This will write the ClientID into the place where it is needed. Anything within the <% %> tags is executed server side. That means that this has to be either VB or C# code (whichever you're using for your server side code which will send the page to the server and then send a new page back to the client)...
                        Did you not understand what I was trying to say here?

                        Originally posted by stefbek97
                        Do you agree that server control attributes and properties can me manipulated within a Javascript function? Also by using document.getEle mentById('<%= ServerControlID .ClientID %>');
                        you can access those controls?
                        You cannot manipulate Server Control attributes and properties with JavaScript.
                        I said this already (see post #10). Dormilich is right, once the server code is finished it generates text (HTML is just text) that is sent to the browser. The browser then reads the HTML-text that was generated by the server and displays things accordingly. You cannot access server-side controls once the page has been sent to the browser because all server-side objects are destroyed once the page is sent.

                        JavaScript works in the browser. It cannot access anything on the server for 2 reasons...there is no persistent connection open between the browser and the server...and the server-side controls do not exist after the page has been sent to the browser.


                        Originally posted by stefbek97
                        My main problem are these lines for code....
                        In the following code:
                        Code:
                        var variable = "TotalSteps";
                        var element = "'" + '<' + '%' + '= ' + 'txt' + variable + '.ClientID' + ' %' + '>' + "'"
                        You are declaring a JavaScript variable that contains a String that contains "<%=txtTotalSte ps.ClientID %>"

                        I think you were expecting this to call the server-side code to get the ClientID of the "txtTotalSt eps" TextBox...But this is not going to accomplish anything because this is just a String stored into a variable in your JavaScript code. You cannot call server code from JavaScript (without making a request to the server)

                        In other words, what you have here doesn't make any sense.


                        I mentioned before that you can pass the HTML (client side) text box element into the function that calculates the average. From there you can use the .parentNode property of the HTML text box element to try and find the row that the text box belongs to.

                        In this case you don't even need to use the ClientID. You just pass a reference to the function like this:

                        C# code:
                        Code:
                         txt1.Attributes["OnBlur"] = "CalcAverage(this)";
                        Notice how I'm passing "this" to the CalcAverage method? "this" is JavaScript that refers to the HTML text box element.

                        You have to change your CalcAverage method so that it takes a parameter in order for you to be able do anything with the element passed into the CalcAverage method:

                        JavaScript code:
                        Code:
                        <script language="javascript" type="text/javascript">
                          function CalcAverage(textBoxElement) {
                        
                          }
                        Now, from here you can do a lot of things to accomplish what you want.

                        You can try what I suggested with the .parentNode of the HTML text box element to try and find a reference to the row that the text box belongs to......

                        Or you could try retrieving a reference to the table that contains all of the text boxes, use the document.getEle mentsByTagName method to retrieve all of the rows in the table ("tr" elements)...and then use the document.getEle mentsByTagName method again grab all input elements... and then check if the row contains the text box element that caused the onblur event.

                        There are many ways to solve this problem.

                        Please re-read this thread (because I have said all of this already but I think you've ignored what I was saying...).

                        If you don't understand something that we are saying please either look it up using google or say that you don't understand and we'll try to explain.

                        -Frinny

                        Comment

                        • stefbek97
                          New Member
                          • Aug 2009
                          • 54

                          #27
                          Re

                          Thats for the reply. I do understand. I have tried using "this" but keep getting the same errors. I understand you can not use the server controls in javascript and maybe did not word it correctly. But accessing the HTML for them is pretty much the same meaning "You have server controls and you can manipulte what they display on the client". But I am not trying to teach anyone. I have been looking for code to find the parentNote and find other controls in that row but so far have not had any success. I though I could build up the clientID of the .Net control but that does not work.

                          Code:
                          <script language="javascript" type="text/javascript"> 
                            function CalcAverage(variable) { 
                          
                          var element = "'" + '<' + '%' + '= ' + 'txt' + variable + '.ClientID' + ' %' + '>' + "'"
                            }
                          and call it like this

                          txtTotalSteps.A ttributes["OnBlur"] = "CalcAverage('T otalSteps')";

                          But have not had success yet.......

                          Comment

                          • Frinavale
                            Recognized Expert Expert
                            • Oct 2006
                            • 9749

                            #28
                            ClientID is a property of the ASP.NET TextBox control.

                            ClientID is not a valid property, or id of anything client side.

                            For example (C# code):
                            Code:
                             aLabel.Text = txtTotalSteps.ClientID;
                            Will display something like "ctl00_cphBody_ txtTotalSteps" in the label.
                            This string ("ctl00_cphBody _txtTotalSteps" ) is the ID attribute of the HTML <input type="text" /> that represents the ASP.NET TextBox (txtTotalSteps) in the browser.

                            Hmm..that is a little confusing...let me try to re-word this. Your ASP.NET TextBox control is rendered as an <input type="text" /> HTML element. It is given a unique id...."ctl00_cp hBody_txtTotalS teps"... so that the page's HTML is valid and so that you can access this element using JavaScript.

                            When the ASP.NET TextBox is rendered as HTML it looks like:
                            Code:
                            <input type="text" id="ctl00_cphBody_txtTotalSteps" name="...."  onblur="CalculateAverage(this)"/>

                            Can you see how the following JavaScript doesn't make sense?
                            Code:
                            var element = "'" + '<' + '%' + '= ' + 'txt' + variable + '.ClientID' + ' %' + '>' + "'"
                            An element with the id "<%=txtTotalSte ps.ClientID %>" doesn't exist on the page....but an element with an id of "ctl00_cphBody_ txtTotalSteps" does. You need to use the "ctl00_cphBody_ txtTotalSteps" ID in with the JavaScript document.getEle mentID() method to retrieve a reference to the HTML <input type="text"> element.

                            The way you can access the "ctl00_cphBody_ txtTotalSteps" ID in your server code is through the ASP.NET TextBox's ClientID property.

                            You can write the value of this ID directly into your JavaScript when the page is being rendered by the server to be sent to the browser. You can either dynamically generate the JavaScript entirely in your C# code and register it with the page (as you did originally)...o r you can write the JavaScript in your ASP code and use ASP syntax execute server-side code that will write the ClientID into the page as it's being rendered.

                            In ASP anything in <% %> is executed on the server....so to write the ClientID of the ASP.NET TextBox into the page you would have: <%Response.Writ e(txtTotalSteps .ClientID);%> or if you want to use the short hand version you can use <%=txtTotalStep s.ClientID;%>.. ..When you look at the HTML source code in the browser you will notice that <%=txtTotalStep s.ClientID;%> is not there...but the text "ctl00_cphBody_ txtTotalSteps" is in it's place. That is because everything between the <% %> was executed server side to generate the text that is displayed client side. You cannot use JavaScript code to try and dynamically generate ASP code since JavaScript runs client-side in the browser and ASP code is executed on the server before the page is sent to the browser.


                            Do you understand this before we start getting into the parentNode stuff?

                            -Frinny

                            Comment

                            • Frinavale
                              Recognized Expert Expert
                              • Oct 2006
                              • 9749

                              #29
                              The answer in pure JavaScript....

                              Here is a working example of a table that has 2 rows, each with 2 textboxes in them.
                              Each textbox calls the calculateAverag e() method and passes a reference to itself into the method during the onblur event.

                              The calculateAverag e() method uses the textbox element passed into it to find a reference to the row that the textbox belongs to. From there it retrieves all textboxes for the row and calculates the average. Once it's found the average it displays it in the <span> that is used to display the average (I picked a span because the ASP.NET Label control is rendered as a span).

                              This example is in pure HTML (not ASP.NET) If you want to see it working, copy the following code into a text document and save it as a .html file (I recommend turning off the line numbers by clicking the "Line Numbers" link before you copy it otherwise a bunch of "#" will appear when you paste what you've copied). After you've saved the file, close the text document and then double click on the HTML file (it should open in your default browser).

                              Please note that the calculateAverag e() method creates JavaScript Number objects based on the values entered into the textboxes. That means that if you enter something that is not a number it will cause an error! It's a rough idea of what you want to do and you're going to have to clean it up so that it works smoothly. Also, please remember that JavaScript is case sensitive. So if you try to call CalculateAverag e() it won't work since the name of the method is calculateAverag e.


                              Code:
                              <html>
                              <body>
                              
                              <table border="1" id="textBoxTable">
                                <tr>
                                  <th>Row</th>
                                  <th>TextBox A</th>
                                  <th>TextBox B</th>
                                  <th>Average</th>
                                </tr>
                                <tr>
                                  <td>Row1: </td>
                                  <td><input type="text" id="txtA" onblur="calculateAverage(this)" value="0" /></td>
                                  <td><input type="text" id="txtB" onblur="calculateAverage(this)" value="0"/></td>
                                  <td><span id="avgForRow1"></span></td>
                                </tr>
                                <tr>
                                  <td>Row2: </td>
                                  <td><input type="text" id="txtA2" onblur="calculateAverage(this)" value="0" /></td>
                                  <td><input type="text" id="txtB2" onblur="calculateAverage(this)" value="0"/></td>
                                  <td><span id="avgForRow2"></span></td>
                                </tr>
                              </table>
                              
                              <script type="text/javascript">
                              function calculateAverage(textBoxElement)
                              {
                                var parentCell = textBoxElement.parentNode;
                                var row = parentCell.parentNode;
                                var inputs = row.getElementsByTagName("input");
                                var spanToDisplayAvg = row.getElementsByTagName("span")[0];
                                var i;
                                var sum = 0;
                                for(i=0; i<inputs.length; i++)
                                {
                                  sum += Number(inputs[i].value);
                                }
                                var average = sum/inputs.length*100;
                                spanToDisplayAvg.innerHTML = average;
                              }
                              </script>
                              
                              </body>
                              </html>

                              Comment

                              • stefbek97
                                New Member
                                • Aug 2009
                                • 54

                                #30
                                I understand. I will test it out.
                                Thanks

                                Comment

                                Working...