HTML form with single text field + preventing postback in Internet Explorer

SudheerKovalam picture SudheerKovalam · Apr 16, 2009 · Viewed 8.5k times · Source

I have noticed a rather strange behaviour in IE.

I have a HTML form with a single input text field and a submit button

On Submit click I need to execute a client side JavaScript function that does the necessary.

Now when I want to prevent the postback in the text field (on enter key press)

I have added a key press JavaScript function that looks like this:


<input type=text onkeypress="return OnEnterKeyPress(event)" />

 function OnEnterKeyPress(event) {
            var keyNum = 0;
            if (window.event) // IE
            {
                keyNum = event.keyCode;
            }
            else if (event.which) // Netscape/Firefox/Opera
            {
                keyNum = event.which;
            }
            else return true;  
            if (keyNum == 13) // Enter Key pressed, then start search, else do nothing.
            {
                OnButtonClick();
                return false;
            }
            else
                return true;
        }

Strangly this doesn't work.


But if I pass the text field to the function :

<input type=text onkeypress="return OnEnterKeyPress(this,event);" />

 function OnEnterKeyPress(thisForm,event) {
            var keyNum = 0;
            if (window.event) // IE
            {
                keyNum = event.keyCode;
            }
            else if (event.which) // Netscape/Firefox/Opera
            {
                keyNum = event.which;
            }
            else return true;  
            if (keyNum == 13) // Enter Key pressed, then start search, else do nothing.
            {
                OnButtonClick();
                return false;
            }
            else
                return true;
        }

I am able to prevent the postback.

Can anyone confirm what is exactly happening here??

the HTML form has just one text box and a submit button

The resultant o/p of the JavaScript function executed on submit is displayed in a HTML text area in a separate div.

Answer

SudheerKovalam picture SudheerKovalam · Apr 17, 2009

Found out a work around for this issue.

i just found out that in IE, if,in a form, there is just one text field and one submit button, pressing enter results in form submit. However if there are more than one text boxes, IE doesn't auto postback the form on enter press, instead it fires the button's onclick event.

So i introduce a hidden text field in the form and everything works magically. I donot even need to handle the onkeypress event for the text field.

<Form>
    <input type="text" />
    <input type="text" style="display:none"/>
    <input type="submit" onClick="callPageMethod();return false;"/>
</Form>

This works perfectly for me!!

This is not an issue in FF, as pressing enter directly results in call to submit button's onclick event.