3

I'm trying to run some javascript before my button's click event happens on the server side, but the javascript code runs, and the server side code runs right after that no matter what. Here's what I have:

<script type="text/javascript" language="javascript">
  $(document).ready(function() {
    SubmitClick = function() {
        if ($("#<%= fuFile.ClientID %>").val() == "") {
            $("#error").html("File is required");

            return false;
        }
    }
  });
</script>

<asp:FileUpload ID="fuFile" runat="server" />

<asp:Button ID="btnSubmit" runat="server" Text="Submit"
  OnClientClick="SubmitClick()" UseSubmitBehavior="false"
  OnClick="btnSubmit_Click" />

<span id="error"></span>

I thought that setting UseSubmitBehavior="false" and returning false in the javascript function would work, but it's not. My error message gets displayed for a second before the server side code runs.

What am I doing wrong here?

1

4 Answers 4

12

Typically to cancel a client click you would add this return false;

You can update your code to do this and it should work: OnClientClick="return SubmitClick();"

Sign up to request clarification or add additional context in comments.

Comments

6

If you are using JQuery:

$btn.on("click", function (e) {
    e.preventDefault();
}

1 Comment

You will need to combine this with setting UseSubmitBehavior back to true for this to work, otherwise it just posts back regardless.
3

What worked for me was: Remove OnClientClick="SubmitClick()" and set UseSubmitBehavior back to true.

Then change your $(document).ready() method to

$(document).ready(function () {
    $('#btnSubmit').click(function () {
        if ($("#<%= fuFile.ClientID %>").val() == "") {
            $("#error").html("File is required");

            return false;
        }

        return true;
    });

});

Comments

0

You need to return the cancellation of the submitted behavior using return in OnClientClick event.

try this

OnClientClick="return SubmitClick()"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.