admin管理员组

文章数量:1357377

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

$('#text_ment').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_menst">'+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 "".

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

$('#text_ment').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_menst">'+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 "".

Share Improve this question asked Jun 15, 2011 at 9:03 TaylorMacTaylorMac 9,00221 gold badges77 silver badges105 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

How about event.preventDefault()

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

try this one event.stopImmediatePropagation()

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

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

$('#text_ment').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_menst">'+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 ?

Answer here http://jsfiddle/Z9KMb/

本文标签: javascriptHow to disable EnterReturn Key After a function is executed because of itStack Overflow