calling javascript function on OnClientClick event of a Submit button
Asked Answered
H

3

8

In my asp.net page, I have three text boxes and one button.
First two text boxes are being used to get the value from the user and third one is being used to show the sum of first two boxes.

I am calling a javascript function to sum the values and show the result value on OnClientClick event of that BUTTON.

JS function is working fine but when I am pressing button to get the sum, it shows the result in third text box and just then the page is being post-back and result value becomes disappear from the third text box.

Why the post-back is called by the button?
I don't want page to be post-backed on click of submit button.

Any suggestion is appreciated.

Hermanhermann answered 7/6, 2013 at 8:3 Comment(0)
M
26

OnClientClick="SomeMethod()" event of that BUTTON, it return by default "true" so after that function it do postback

for solution use

//use this code in BUTTON  ==>   OnClientClick="return SomeMethod();"

//and your function like this
<script type="text/javascript">
  function SomeMethod(){
    // put your code here 
    return false;
  }
</script>
Milestone answered 7/6, 2013 at 8:15 Comment(2)
i have already added "return false" at the end of javascript function even then it is occuring.Hermanhermann
be sure in button you have call method like this OnClientClick="return SomeMethod();"Milestone
J
5

The above solutions must work. However you can try this one:

OnClientClick="return SomeMethod();return false;"

and remove return statement from the method.

Jacksmelt answered 7/6, 2013 at 8:29 Comment(1)
What is a use of return false; in this answer, I believe it will never executes as return SomeMethod() will stop rest of execution after returning valueCarolinacaroline
M
2
<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="btnGet_Click" OnClientClick="return callMethod();" />
<script type="text/javascript">
    function callMethod() {
        //your logic should be here and make sure your logic code note returing function
        return false;
}
</script>
Milestone answered 7/6, 2013 at 8:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.