How to disable submit behaviour of asp:ImageButton?

I will assume you have some sort of input controls and you don’t want an enter keypress to auto submit when a user accident hits the enter key. If so you can attach a javascript onkeypress event to each control that you want to disable this behavior for.

function disableEnterKey(e)
{
     var key;
     if (window.event) key = window.event.keyCode; // Internet Explorer
     else key = e.which;

     return (key != 13);
}

// In your aspx file Page_Load do the following foreach control you want to disable
// the enter key for:
txtYourTextBox.Attributes.Add("OnKeyPress", "return disableEnterKey(event);");

If you need to disable the Enter key submitting form completely. case use the OnKeyDown handler on <body> tag on your page.

The javascript code:

if (window.event.keyCode == 13) 
{
    event.returnValue = false; 
    event.cancel = true;
} 

With JQuery this would be much cleaner, easier and the recommended method. You could make an extension with:

jQuery.fn.DisableEnterKey =
    function()
    {
        return this.each(function()
        {
            $(this).keydown(function(e)
            {
                var key = e.charCode || e.keyCode || 0;
                // return false for the enter key
                return (key != 13);
            })
        })
    };

// You can then wire it up by just adding this code for each control:
<script type="text/javascript" language="javascript">
    $('#txtYourTextBox').DisableEnterKey();
</script>

Leave a Comment