48

I was looking for a way to do this, got a few scripts, but none of them is working for me.

When I hit enter in my textboxes, it shouldn't do anything.

I have tried a few JavaScript and jQuery scripts, but nothing is working for me.

$(document).ready(function() {
    $('#comment').keypress(function(event) {
        if (event.keyCode == 13) {
            event.preventDefault();
        }
    });

    $('#comment').keyup(function() {
        var txt = $('#comment').val();
        $('#comment').val(txt.replace(/[\n\r]+/g, " "));
    });
});
Warren Sergent
  • 2,257
  • 3
  • 34
  • 38

10 Answers10

51

This works for me.

$('textarea').keypress(function(event) {
    if (event.keyCode == 13) {
        event.preventDefault();
    }
});

jsFiddle.

Your second piece looks like it is designed to capture people pasting in multiple lines. In that case, you should bind it to keyup paste.

alex
  • 438,662
  • 188
  • 837
  • 957
  • it is working in fiddle but if i put that script in my local,it s not working. –  Mar 30 '11 at 06:56
  • @user You may have an error in your JavaScript, enable your console and look for any errors. – alex Mar 30 '11 at 06:57
  • You should use $('textarea').on('keypress', function (){blah;}); so that you can kill it programmatically if needed using .off() – MetalPhoenix Aug 12 '15 at 16:37
  • @MetalPhoenix The code I have translates to the `on()` method. Determining how to write the code depends on its purpose - for some cases, you don't ever need to unbind it, which means the code above is fine. If it weren't the case, you'd simply write it differently. – alex Aug 13 '15 at 23:08
  • I agree but since they are, essentially, the same but with the forward thinking of being able to unbind, why *wouldn't* you do that? Is there a performance difference? – MetalPhoenix Aug 14 '15 at 13:17
  • @MetalPhoenix In order to unbind I would need a reference to the function or give it a unique namespace. – alex Apr 04 '16 at 16:30
  • Not entirely true: http://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery But this is only important if you're stacking handlers (which you shouldn't do because it's not always clear what you're doing and can lead to debugging problems). The point remains that you can just call `$("obj").off("event");` and be done with it. – MetalPhoenix Apr 06 '16 at 09:07
  • @MetalPhoenix There can end up having many listeners, due to jQuery plugins for example. Stacking listeners is fine if the situation calls for it. – alex Apr 06 '16 at 09:10
  • I agree with you. It's also good forward thinking to make it so you can de-register a handler later on if you need to so that you don't have to change the code for each one later or try to figure out which "thing" is making the textbox do something unexpected. Also, doing it with `.on` allows you to de-register a single listener without killing them all. – MetalPhoenix Apr 06 '16 at 12:15
  • @MetalPhoenix You realise that `keydown()` with an argument maps to `on()` too, right? I also try to follow YAGNI. If my code doesn't need to unbind at the current time, I won't write it so it can be in the future. If I need it in the future, I'll modify it. I guess people's opinion on this is different. – alex Apr 06 '16 at 13:08
  • My experience shows that if you don't put it in before it's deployed, your company isn't going to want to pay to change things later. – MetalPhoenix Apr 06 '16 at 13:12
  • thank you..perfect and simple – Debbie Kurth Mar 04 '21 at 23:54
18

If you want to prevent Enter key for specific textbox then use inline js.

<input type="text" onkeydown="return (event.keyCode!=13);"/>
Akshay
  • 284
  • 2
  • 6
14

It stops user to press Enter in Textbox & here I return false which prevent form to submit.

$(document).ready(function()
    {
        // Stop user to press enter in textbox
        $("input:text").keypress(function(event) {
            if (event.keyCode == 13) {
                event.preventDefault();
                return false;
            }
        });
});
PHP Ferrari
  • 14,189
  • 25
  • 79
  • 144
7

Works for me:

$('#comment').keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
    }
});

http://jsfiddle.net/esEUm/

UPDATE

In case you're trying to prevent the submitting of the parent form rather than a line break (which only makes sense, if you're using a textarea, which you apparently aren't doing?) you might want to check this question: Disable the enter key on a jquery-powered form

Community
  • 1
  • 1
polarblau
  • 17,061
  • 7
  • 59
  • 81
  • Which browser are you using? Are you receiving any other JS errors? Is the selector correct? Have you tried to `return false;` as suggested here? – polarblau Mar 30 '11 at 07:27
5

I found this combine solution at http://www.askmkhize.me/how-can-i-disable-the-enter-key-on-my-textarea.html

$('textarea').keypress(function(event) {

if ((event.keyCode || event.which) == 13) {

    event.preventDefault();
    return false;

  }

});

$('textarea').keyup(function() {

    var keyed = $(this).val().replace(/\n/g, '<br/>');
    $(this).html(keyed);


});
Gijs Overvliet
  • 2,514
  • 3
  • 25
  • 35
user1853583
  • 69
  • 1
  • 6
3

If you want to disable for all kind of search textbox. Give all them a class and use that class like 'search_box' following.

//prevent submission of forms when pressing Enter key in a text input
$(document).on('keypress', '.inner_search_box', function (e) {
    if (e.which == 13) e.preventDefault();
});

cheers! :)

Nikunj Dhimar
  • 1,858
  • 14
  • 20
0

I don't understand why everybody here is suggesting to use jquery. There is a very simple method for it for a specific input element field. You can use its onKeyDown attribute and use e.preventDefault() method in it. Like this:

<input type="text" onKeyDown={(e) => e.preventDefault()}/>

Note: This is React JSX way of using this attribute you can use HTML basic way.

A.Khan
  • 47
  • 7
0

Use global selector $('input')...if you use multiple text boxes on page the ID ('#comment') will cause problems. And when using dynamic content bind it using .live e.g.

$('input:not(textarea)').live('keypress',function(e) {
    if (e.which == 13) return false;
    if (e.which == 13) e.preventDefault();
});

(Disable enter for text boxes and leaves enter enabled for text areas)

Marc Uberstein
  • 12,143
  • 3
  • 41
  • 68
  • textarea ...basically using the tag name instead of a class or ID selector – Marc Uberstein Mar 30 '11 at 07:06
  • Okay, try to debug it by using alert e.g. alert(e.which); . Check the text that is alerted and alter your if statement. (is there any javascript errors on page?; AND can you show me your html for the textarea section you are using) – Marc Uberstein Mar 30 '11 at 07:22
  • Okay miss read that one... use $('input:not(textarea)') . this will effect all text boxes and non of the textareas. (I will alter my answer) – Marc Uberstein Mar 30 '11 at 07:27
  • But it is always good to keep the enter active for textareas, incase you have to use a textarea - http://jsfiddle.net/F3pyZ/ if you disable the script the form will submit. (Did you manage?) – Marc Uberstein Mar 30 '11 at 07:53
0

Variation on Alex solution, but using plain javascript code. Can be used for any key. The prevent default, stops form submission. This is what is working for me.

<input type="text" placeholder = "0.0"  onkeydown = "noareturnkey(event)">

Then the simple javascript code:

function noreturnkey(event) {
  var x = event.which || event.keyCode;
  if (x == '13')
   event.preventDefault();
}
Debbie Kurth
  • 262
  • 2
  • 12
0
<script type="text/javascript">

   function stopRKey(evt) { 
     var evt = (evt) ? evt : ((event) ? event : null); 
     var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
     if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} 
   } 


document.onkeypress = stopRKey; 

</script>

http://webcheatsheet.com/javascript/disable_enter_key.php

alony
  • 10,325
  • 3
  • 34
  • 46
ariel
  • 9
  • 1