Disabling the form submit on press of ENTER key

At times you would have seen that when you are filling a form on a website and you hit “ENTER” key the form gets submitted. As a developer you may have come across a situation where you would have wanted to prevent this action. The solution to this is to disable the “ENTER” key using javascript. Here’s a code snippet that disables “Enter” key in HTML textbox:

<script type="text/javascript">

// <![CDATA[
function disableEnterKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (elem.type=='text'))  {return false;}
}

document.onkeypress = disableEnterKey;
// ]]>

</script>

I was working on custom reports in Magento. After the reports were done, during unit testing I noticed that in one report “Stock Price Report” when I enter a filter value in textbox and hit enter the form was submitted while in the other report “Stock Report” when I hit enter after entering a value in filter textbox it did not submit.

 

 

When the report was submitted on press on “Enter” key it was causing issue, the filter textbox did not show the value that was enetered by the user on display of report and the sorting of the report did not work.

 

 

The issue in “Stock Price Report”  was that when the filter form was submitted on press of “ENTER” key the form data was added passed querystring directly while on press of  “Show Report” button the form data was first serialized and then sent. On observing both the reports I saw that the “Stock Price Report” that got submitted on hit of “ENTER” key just had one textbox while the “Stock Report” had two textboxes so the conclusion was that if there are more than one textbox in the report filter form then the form will not submit on press of “ENTER” key. So I added the javascript to disable the “ENTER” key in the protected function _prepareForm used to create the filter form as below:

protected function _prepareForm()
{
.
.
.
$element = $fieldset->addField('product_sku', 'text', array(
'name' => 'product_sku',
'label' => Mage::helper('productreports')->__('SKU'),
));

$element->setAfterElementHtml("<script type=\"text/javascript\">
function disableEnterKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (elem.type=='text'))  {return false;}
}

document.onkeypress = disableEnterKey;
</script>");
.
.
.

Leave a Comment

Back to top