Frage

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!

War es hilfreich?

Lösung

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

Andere Tipps

Close dialog on ESC, just add an keyup listener to document and call $.unblockUI if the key code is equal to 27.

​​$(document).on('keyup', ​​​function(e) {
  if (e.which === 27) { // Escape key
    $.unblockUI();
  }
});​

For the form, just add an event listener to the input field in the dialog. It's basically the same.

​​$('#the-input').on('keyup', ​​​function(e) {
  if (e.which === 13) { // Enter key
    // AJAX maybe?
    $.post('your/url', { data: $(this).val() }, function(response) {
      $.unblockUI();            
    });
  }
});​

Edit

You assign those listeners after the DOM has been loaded. So your loaded script file would contain:

$(document).ready(function() {
    // Code from the two listings above here

    // Trigger blockUI by click on an link for example
    $('a').on('click', function(e) {
        e.preventDefault();

        $.blockUI({ message: $('#your-form') });
    });
});

javascript:

("#yourInput").keyup(function(e){
    switch (e.keyCode) {
    case 13: # enter
    # logic
    case 27: # esc
    # logic
    }
})
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top