2

I have an ASP.Net WebForms application where I am using jQuery validation. There are several buttons to submit the form, each with different options on the back end.

I have a custom validateForm() function that I can assign to the OnClientClick event of all the buttons, but I'm hoping for a more elegant solution where I don't have to specifically give each button the OnClientClick property.

So basically, is it possible to capture the $(form).submit() event before an asp button is submitted? Without using the OnClientClick attribute?


Solved: My issue was actually not because I couldn't catch the submit, but because the buttons were <a> links instead of inputs. I didn't realize this and made the post while at home trying to fix it from memory.

Any of the below solutions should work in the scenario above with actual submit buttons

MichaelM
  • 964
  • 7
  • 20
  • 2
    what ryan said. or you could attach 'click' listeners to individual buttons. `.on('click', ...)`. – wazz Apr 16 '18 at 22:24

2 Answers2

1

Just attach a listener to the submit event:

$('form').on('submit', function (event) {
    // Do whatever you need to do here ...
    // You could also do `event.preventDefault();`,
    // if you wanted to stop the submit.
});
ryanpcmcquen
  • 6,285
  • 3
  • 24
  • 37
-1

You can use onsubmit event that will execute a JavaScript when a form is submitted from any button.

<form id="form1" runat="server" onsubmit="return ValidationFunction();">

And your JS function should return true or false as

function ValidationFunction() {
    // Your jQuery validation
    if (isValide) {
        return true;
    }
    else {
        return false;
    }
}

Another option using JQuery to attaches an event handler to form submission

$(document).ready(function () { // << to make sure DOM is loaded
    $('#form1').on('submit', function (e) {

        e.preventDefault(); // << the default action of the event will not be triggered
        var isValide = false;

        if (isValide) {
            alert('ok');
            this.submit();
        }
        else {
            alert('Not Valid');
        }
    });
});
ElasticCode
  • 7,311
  • 2
  • 34
  • 45