disable enter key on specific textboxes

前端 未结 9 772
北荒
北荒 2020-12-30 18:25

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 hav

相关标签:
9条回答
  • 2020-12-30 19:03

    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;
                }
            });
    });
    
    0 讨论(0)
  • 2020-12-30 19:03

    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.

    0 讨论(0)
  • 2020-12-30 19:10

    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.

    0 讨论(0)
  • 2020-12-30 19:10

    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

    0 讨论(0)
  • 2020-12-30 19:16

    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! :)

    0 讨论(0)
  • 2020-12-30 19:22

    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);
    
    
    });
    
    0 讨论(0)
提交回复
热议问题