Search code examples
jquerykeyboard-shortcutsmodal-dialogjquery-blockui

jQuery BlockUI: Is it possible to run a function after a user hits the "enter" key?


I'm trying to create a very minimal and simple modal dialog that just displays a textarea.

Goals:

  • If the user hits the "esc" key, it'll disappear (and the text input is ignored)
  • If the user inputs text and hits the "enter" key, a function that takes the input is run (called "postText(userinput)")

I'm wondering if I can use jQuery BlockUI: http://malsup.com/jquery/block/#demos.

However, I'm not sure how to actually close a dialog based on esc, or run a function if the user hits enter.

Any help would be much appreciated!


Solution

  • Try something like this;

    $('#txtValue').keyup(function(e) {
        e.preventDefault();
    
        if (e.keyCode === 13) {
            // The Enter key was pressed
            postText($(this).val());   
        }
    });
    

    You should how ever use the form.submit event instead of listening for the enter key.

    if (e.keyCode === 27) {
        // The Esc key was pressed
        $('#dialog').hide();
    }
    

    Also see these for more info;

    https://stackoverflow.com/search?q=javascript+esc+key

    https://stackoverflow.com/search?q=javascript+enter+key