开发者

Javascript Shift+Enter (Firefox)

Had a look and found some things on this, but nothing seems to work as I'd like it.

Initially I had my solution working with internet explorer and chrome, but not firefox (which is unsatisfactory for me to not have working)

What I'm looking for is a simple text area, which sends data on enter key, but creates a new line on Shift+Enter. The following is what I have

function goReturn(e,str) {

  var e = (window.Event) ? e.开发者_JS百科which : e.keyCode;
  if (e.shiftKey && e=="13") {
    document.getElementById("wall").value = 
        document.getElementById("wall").value+"\n";
  } else if(e=="13"){
    // ...continue to send data
  }
}

This sends the data on enter, but also sends the data on shift and enter (which is the problem I have).

Thanks for any assistance


Catch the submit call in your form (onsubmit="..."). There, check if the last enter was in combination with shift. If yes, return false to the submit request.

You can also try if returning false on e.shiftKey && e=="13" is sufficient.


You should be able to cancel the event propagation through e.cancel = true; but I see that currently you're overwriting the e variable (event object). If you would change your code to the following, you should be fine:

function goReturn(e_obj,str) {

  var e = (window.Event) ? e_obj.which : e_obj.keyCode;
  if (e.shiftKey && e=="13") {
    document.getElementById("wall").value = 
        document.getElementById("wall").value+"\n";
    e_obj.cancel = true;
  } else if(e=="13"){
    // ...continue to send data
  }
}


I have written a jQuery plugin for my own use case and it might fit yours: http://cburgmer.github.com/jquery-shiftenter/

The plugin takes care of handling the return key and also displays a hint on focus to explain the behaviour.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜