Combine Javascript and ASP.Net

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • stefbek97
    New Member
    • Aug 2009
    • 54

    Combine Javascript and ASP.Net

    Hello Everyone,

    I am ready to pull my hair out with this situation.
    Here is what my application Looks like.

    I have a Master Page,Content Page with a Tab Container and A user Control inside the Tab Panel of the Container.

    In the user Cotrol I have a Table with Textboxes. My assignment is to Calculate the average of two textboxes and diplay in a Label. I need to do that on the client so that there is no postback so I try to use javascript.

    A declared a Javascript Function and try to call it OnBlur of the textbox. How do I pass the values of txt1 and txt2 to the function?
  • ThatThatGuy
    Recognized Expert Contributor
    • Jul 2009
    • 453

    #2
    Define the function as
    Code:
    calculate(val1,val2)
    {
    //code for average
    }
    call the function on button click event and pass the parameters

    Comment

    • planetboy1982
      New Member
      • Jan 2010
      • 7

      #3
      make a func to do calculation in java script then use it in events of textbox u use in your tab panel

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        Check out this article on How to use JavaScript in ASP.NET.

        Please note that you have to use the ClientID of the TextBoxes in order to retrieve the TextBox elements in your JavaScript Code since you are using a MasterPage. The ClientID property is there to give you access to the ID that the element is given when it is rendered as HTML...

        Say you have a TextBox with the ID="TextBox1". When TextBox1 is rendered it is given a unique id. Since you can have multiple controls or pages with a TextBox with the ID="TextBox1", ASP.NET takes it onto itself to ensure that these TextBoxes are given unique IDs when they are rendered as HTML. This means that the ID given to TextBox1 in your user control in your MasterPage might look this in it HTML:

        Code:
        <input type="text" id="ctl00_IdOfPlaceHolder_IdOfUserControl_TextBox1" ..... />
        See how different this ID is from the ID you gave the TextBox in your server code? The way to access this ID is through the TextBox's ClientID property.

        Here is an example of JavaScript code that is not dynamically generated (that is just part of the page for the user control):
        Code:
        <script type="text/javascript">
          function avg()
          {
            //retrieving the value from the TextBox1 element.
            var firstValue = document.getElementById('<%=TextBox1.ClientID;%>').value;
            //retrieving the value from the TextBox2 element.
            var secondValue = document.getElementById('<%=TextBox2.ClientID;%>').value;
        
             //now use these values to calculate the average...
          }
        </script>
        In this JavaScript code I am using the TextBox's ClientIDs to retrieve the text box elements. 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). In this example I used C# code. If I were to have used VB.NET code it would have been very similar except that there wouldn't be any semicolon at the end of the ClientID.

        (Please do not use Response.Write in your C#/VB.Net code because it will write whatever it is you're writing above the <html> start tag).

        -Frinny

        Comment

        • stefbek97
          New Member
          • Aug 2009
          • 54

          #5
          Thanks every one for the code and ideas. Here is the situation. Lest say I have 5 rows with 3 columns. In each row I have 2 Textboxes and 1 Label. What I need to do is have the Javascript calculate onBlur of the text box.I need to find the textbox that caused the event and the one next to it in the same row that will be used to calculate average. and display it in the label that is in the same row. Do i need a javascript function for Each row?? Also where do I place the Javascript, into the master page , Content Page or User Control.

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            No you don't need a JS function for each row.
            You can pass the object that caused the event into the function. You can access it using the "this" keyword.

            For example here's the average function that takes a TextBox element as a parameter:
            Code:
            function avg(tbElement)
            {
              
            }
            Here's the code that passes the TextBox element into the avg function:
            Code:
            onblur="avg(this)"

            It would probably be a good idea to keep track of the grid that contains the TextBoxes in your average function so that you can retrieve all of the rows...loop through the rows and do your average calculation.

            Code:
            function avg(tbElement)
            {
                var grid = document.getElementById('theIdOfTheGrid');
            }

            You can use the getElementsByTa gName() method to retrieve the rows in the grid ("tr" is the tag name). You can likewise use this method to retrieve all of the text box elements for each row in the grid (tag name is "input" you can check the type property of each input element you retrieve to make sure it's type "text").

            You can put the JavaScript at any level you want to.
            I would keep it at the UserControl level though because it's likely that this method wont have to be used by anything else. You could store it in an external JavaScript file if you want to...and just link to it when the UserControl is active...meh.

            Why didn't you just ask your real question first of all??

            -Frinny

            Comment

            • stefbek97
              New Member
              • Aug 2009
              • 54

              #7
              ok so I would need to Give the row of the table a name, how would I pass the row onBlur of the textbox and loop through the row and find the controls. I have tried passing this and get a javascript null object error.

              Comment

              • Frinavale
                Recognized Expert Expert
                • Oct 2006
                • 9749

                #8
                I edited my post so please look it over again.
                What you'll do is loop through all of the rows and retrieve the inputs for each row...then you loop through each input retrieved and check if it has a "type='text '" and if so check if it's the same element passed into the method. If it is then that's the row where the event happened.

                This question is probably best to ask a JavaScript expert because they'd probably know more about this than I do. I've moved your question to the JavaScript Forum.

                -Frinny

                Comment

                • stefbek97
                  New Member
                  • Aug 2009
                  • 54

                  #9
                  Do I have to use HTML controls or can I do the same with ASP.Net Textbox,Label?
                  Thanks

                  Comment

                  • Frinavale
                    Recognized Expert Expert
                    • Oct 2006
                    • 9749

                    #10
                    When you are using JavaScript you have to work with HTML elements.

                    Your ASP.NET controls are rendered as HTML controls. You cannot use .NET controls in your JavaScript because they exist on the server and JavaScript works in the browser, client-side.

                    You can access the HTML elements that represent the ASP.NET controls using JavaScript.

                    -Frinny

                    Comment

                    • stefbek97
                      New Member
                      • Aug 2009
                      • 54

                      #11
                      Combine Javascript and ASP.Net

                      Here is the code for what I am currently doing and i know it is a hack and only works with one row of my table. Maybe we can find a way to modify it and make it work without hardcoding those Control Name's.

                      Code:
                      protected void Page_Load(object sender, EventArgs e)
                          {
                              string MyScript = "function CalcAverage() {" +
                              "var nSteps; " +
                              "var nDays; " +
                              "var nAverage; " +
                              "nSteps = 0; " +
                              "nDays = 0; " +
                              "nAverage = 0; " +
                              "nSteps = document.getElementById('ctl00_ctl00  _cphBody_cphBody_txtTotalSteps').value; " +
                              "nDays = document.getElementById('ctl00_ctl00_cphBody_cphBody_txtDaysOfSteps').value; " +
                      
                              "if ((nSteps != 0) && (nDays != 0)) " +
                              "{ " +
                              "nAverage = (nSteps / nDays); " +
                              "nAverage = Math.round(nAverage); " +
                              "document.getElementById('ctl00_ctl00_cphBody_cphBody_lblAvgSteps').value = (nAverage); " +
                              "} " +
                              "else " +
                              "{ " +
                              "document.getElementById('ctl00_ctl00_cphBody_cphBody_lblAvgSteps').value = 0;}; " +
                              "}; ";
                      
                              ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "MyScript", MyScript, true);
                      
                              txtTotalSteps.Attributes["onblur"] = "CalcAverage()";
                              txtDaysOfSteps.Attributes["onblur"] = "CalcAverage()";
                          }

                      Comment

                      • Frinavale
                        Recognized Expert Expert
                        • Oct 2006
                        • 9749

                        #12
                        Well.......I told you how to do this already.

                        First of all replace "ctl00_ctl00_cp hBody_cphBody_l blAvgSteps" with lblAvgSteps.Cli entID.

                        You are probably going to want to pass the TextBox element that caused the onblur event as a argument to the CalcAverage() method. You have to change the CalcAvarage method to accept the text box as a parameter too....


                        Code:
                          //passing the textbox element as an argument into the CalcAvarage method
                          txtTotalSteps.Attributes["onblur"] = "CalcAverage(this)";
                          txtDaysOfSteps.Attributes["onblur"] = "CalcAverage(this)";

                        Code:
                        string MyScript = "function CalcAverage(txtBoxElement) {" +
                                "var nSteps; " +
                                "var nDays; " +
                                "var nAverage; " +
                                "nSteps = 0; " +
                                "nDays = 0; " +
                                "nAverage = 0; " +
                                "nSteps = document.getElementById('"+
                                 txtTotalSteps.ClientID +
                                 "').value; " +
                                "nDays = document.getElementById('"+
                                 txtDaysOfSteps.ClientID +
                                 "').value; " +
                         
                                "if ((nSteps != 0) && (nDays != 0)) " +
                                "{ " +
                                "nAverage = (nSteps / nDays); " +
                                "nAverage = Math.round(nAverage); " +
                                "document.getElementById('"+
                                 lblAvgSteps.ClientID 
                                 "').value = (nAverage); " +
                                "} " +
                                "else " +
                                "{ " +
                                "document.getElementById('" +
                                 lblAvgSteps.ClientID +
                                 "').value = 0;}; " +
                                "}; ";

                        I'm assuming lblAvgSteps is a Label.
                        An ASP.NET Label is rendered as a <span> element, where the text for the Label is placed as the "inner html" of the span element. So it looks like:
                        Code:
                        <span> This is the Text Property of the of the label </span>
                        Therefore, if you want to change the text of an ASP.NET Label client side, you have to use the innerHTML property of the span element that represents the Label.


                        So you need to change:
                        Code:
                        "document.getElementById('"+
                                 lblAvgSteps.ClientID 
                                 "').value = (nAverage); "
                        To:
                        Code:
                        "document.getElementById('"+
                                 lblAvgSteps.ClientID 
                                 "').innerHTML= (nAverage); "
                        (PS I may have the case wrong for the innerHTML property...doub le check this or it won't work)

                        -Frinny

                        Comment

                        • Frinavale
                          Recognized Expert Expert
                          • Oct 2006
                          • 9749

                          #13
                          You can use the "parentNode " of the HTML text box element to get the parent element of the TextBox...which will give you the Row that it belongs to (make sure to check that the parent element is what you're looking for before you use it).

                          -Frinny

                          Comment

                          • stefbek97
                            New Member
                            • Aug 2009
                            • 54

                            #14
                            Lets see if we can find a Javascript guru that can help us. Since i cant debug javascript I dont know what is causing the errors.

                            Comment

                            • stefbek97
                              New Member
                              • Aug 2009
                              • 54

                              #15
                              I am getting a Javascript Object Required Error. Looks like the Javascript does not recognize the Textboxes.

                              Comment

                              Working...