Question

Hello this is what i have in the head of my file:

function entsub(event)
        {
              if (event && event.which == 13) 
                write1();
              else
            return true;

        }

and in the body, my form is:

<form id="writeform" name="writeform">
  Message: <br />
  <textarea name="message" rows="3" id="message" style="width:90%;" onkeypress="return entsub(event)"></textarea>

  <br />
  <input name="send" type="button" id="send" value="Send" onclick="write1()" />
  <span id="sent"></span>
  &nbsp;&nbsp;&nbsp; <input type="reset" value="Reset" />
  </form>

I need to make it work that when i press enter when i am in the textarea, it does not make a new line but send it [see my <input type="button">]

But it won't work! It keeps making a new line... Using IE8 now.

Was it helpful?

Solution

Use keyCode instead of which.

Depending on the browser, you need to prevent the default action. Check out event.cancelBubble and event.returnValue for IE and event.stopPropagation() and event.preventDefault() for Firefox.

OTHER TIPS

Well i'm not sure what write1() does, but it would be prudent to return false when the condition is met..

function entsub(event)
{
    if (event && event.keyCode == 13) {
        write1();
        return false; //Return false to prevent default execution
                      //Some browsers use event.preventDefault() etc.
    }else{
        return true;
    }
}

Usually the cross browser test is the following:

function entsub(e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        write1();
    } 
    return true;
}

If you want to use jquery, you can do this:

        $(document).ready(function() {

            $("#txtTest").keypress(function(e) {
                var code = (e.keyCode ? e.keyCode : e.which);

                if (code == 13) {
                    doSomething();
                    return false;
                }
            });

        });

        function doSomething() {
            alert("I did it!");
        }

where txtTest is the id of your textarea.

For a non-js related way, I'm pretty sure you can just use an input of type="submit" and it will use enter to submit the form. At that point, you would just move your event to onsubmit.

A cleaner way is to change to <input type="button"> to <input type="submit"> and move the onclick="..." to a onsubmit="..." on the form. This would not require so much error-prone JavaScript and would work in more cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top