Announcement

Friday, 21 March 2014

How to prevent the default action of submit button?

This is my submit button with id as "btnSubmitModification" .

We need to prevent the default action of this submit button i.e., to prevent the
form from submission on click of this button.

<input type="submit" class="button" id="btnSubmitModification" value="Save"/>

Here is the code in script tag.
This is achieved using jquery.

We handle the click event of submit button and pass the parameter to the
event handler function as e.

This is parameter is than used to prevent the default action of submit button i.e., to
prevent the form from submission.

Just write e.preventDefault(); and you are done.

<script type="text/javascript">
    $('#btnSubmitModification').click(function (e) {
        if ($("#txtName").val() != "" && $("#txtName").val() != null) {
            // write your further code here.
            return true;
        }
        else {
            alert('Please enter name.');
            e.preventDefault();
        }
    });
</script>

Alternative way to do the same thing is as: Just write return false and don't pass any
argument to the function.

<script type="text/javascript">
    $('#btnSubmitModification').click(function () {
        if ($("#txtName").val() != "" && $("#txtName").val() != null) {
            // write your further code here.
            return true;
        }
        else {
            alert('Please enter name.');
            return false;
        }
    });
</script>



No comments: