views:

242

answers:

1

I want to suppress line feed in on pressing enter. Instead, I want to submit the form. I know how to submit the form on pressing enter in textarea, but I don't know to supress line feed on pressing enter. I need to hide it from user, I mean I want user not to see that enter made new line even for a moment.

Thank you in advance.

+1  A: 

You can suppress the default key action in a keypress event handler:

textArea.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    if (charCode == 13) {
        evt.returnValue = false;
        if (evt.preventDefault) {
            evt.preventDefault();
        }

        // Do the form submit
        this.form.submit();
    }
};
Tim Down
Thank you! Though I think we need to use "document.getElementById('myForm').submit()" to make it work in FireFox.
nightcoder
That depends on how you're attaching the keypress event handler. If you have a reference to a textarea object then its `form` property will be a reference to its containing form in all browsers, provided it is contained in a form. In my example I was taking advantage of `this` being a reference to the event target, and it should work as it is in all browsers.
Tim Down
I attach the event like this: "<textarea onkeypress='SuppressReturnKeyAndSubmitForm(event);' ... >" and the function is declared like this: "function SuppressReturnKeyAndSubmitForm(e) { ... }" and inside the function "this" points to "window" object which doesn't have "form" property.
nightcoder
OK. In which case I'd suggest passing a reference to the textarea to `SuppressReturnKeyAndSubmitForm` in the `onkeypress` attribute: `<textarea onkeypress='SuppressReturnKeyAndSubmitForm(event, this);' ... >` and changing the function parameters: `function SuppressReturnKeyAndSubmitForm(e, textArea) { ... }`. You can then simply call `textArea.form.submit()` in the function.
Tim Down