How to disable Enter/Return Key After a function is executed because of it?

走远了吗. 提交于 2019-12-24 10:39:08

问题


I have this function where #text_comment is the ID of a textarea:

$('#text_comment').live('keypress',function (e) {

    if(e.keyCode == 13) {
        textbox = $(this);
        text_value = $(textbox).val();

        if(text_value.length > 0) {
            $(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
            $(textbox).val("");
        } 
    }                                               
});

What is happening is the text is appending when the enter/return key is hit (keyCode 13), but it is also moving the text a line down, as the enter/return key is supposed to.

This is occurring even though I set the value of the textbox to "".


回答1:


Answer here http://jsfiddle.net/Z9KMb/




回答2:


How about event.preventDefault()




回答3:


Try and stop your event propagation (See http://snipplr.com/view/19684/stop-event-propagations/) when entering the if(e.keyCode == 13) case.




回答4:


try this one event.stopImmediatePropagation()

$('#text_comment').live('keypress',function (e) {       
          if(e.keyCode == 13) {   
               e.stopImmediatePropagation()
       ///rest of your code
  }
});



回答5:


I've tested this out, this works. The enter does not create a new line.

$('#text_comment').live('keypress',function (e) {

    if(e.keyCode == 13) {
        textbox = $(this);
        text_value = $(textbox).val();

        if(text_value.length > 0) {
            $(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
            $(textbox).val("");
        }
        return false;
    }                                               
});

Although I am wondering, if you don't want to ever have a new line, why are you using a textarea, why not use a input type='text' instead ?



来源:https://stackoverflow.com/questions/6355362/how-to-disable-enter-return-key-after-a-function-is-executed-because-of-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!