简体   繁体   中英

How to pass user input from ASP.NET TextBox to JavaScript function?

I am trying to pull the information that the user inputs in the text boxes and pass the value to a JavaScript function in order to display the result in a "window.alert()" method.

I am currently using ASP.NET. This what I have so far for the ASP.NET front part and for the JavaScript;

 <asp:Button ID="btnCalculateSalary" runat="server" Text="Calculate Salary" OnClick="calcFunction()" />

    <script>
        function calcFunction(c1, c2) {
            c1 = document.getElementById('txtAnnualHours').value;
            c2 = document.getElementById('txtPayRate').value;

            return window.alert("Your Annual Salary is: " + c1 * c2);
        }

This isn't doing what you think:

OnClick="calcFunction()"

Since that's a server-side ASP.NET "control" and not an HTML element, OnClick is referring to ASP.NET's server-side event handlers. But you have a client-side function to be executed. In that case, try:

OnClientClick="calcFunction()"

One important thing to note, however, is that this is still a server-side ASP.NET control. Which means that after processing the client-side click event it may (depending on a number of unrelated factors) still invoke a post-back to the server which will refresh the page. A common source of confusion among beginners is that a quick page refresh will "reset" their client-side state and cause them to suspect that "it isn't working".

Often when all you want to do is perform client-side actions, you may want to skip the server-side controls altogether and just use normal HTML elements.

Another unrelated side note... Your JavaScript function doesn't need those c1, c2 parameters in the function declaration. Values aren't being passed to the function, and passed values aren't being used in the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM