Cancel the form being submitted in javascript

johnWeeGo.jpgI come across this trick every so often so thought it best to write it down. In the AJAX world it seems this is more and more common, why would i ever want to post back again?

If you have a textbox in a form and when the user presses enter you don’t want them submitting that form you can cancel the event in javascript.

Within your MS AJAX js class set a flag to indicate if this object was the one that submitted, then we hook the form submit event and cancel if so.


//in your init
this._keyPressHandler = Function.createDelegate(this, this._onKeyPress);
this._VerifySubmitHandler = Function.createDelegate(this, this.VerifySubmit);
$addHandler(this._Textbox, 'keypress', this._keyPressHandler);           
$addHandler($get("Form"),"submit", this._VerifySubmitHandler);

//two events handlers
    _onKeyPress : function(e) {
        if (e.charCode==13)
            this._submitted = true;
            //do whatever you need to do on enter

    VerifySubmit: function(e)
        if (this._submitted)
            this._submitted = false;
            if (e && e.preventDefault) //FF
            return false; //IE