JQuery UI - dialog closes immediately after opening with onkeypress Enter / Space

I want to open a jQuery UI dialog when the user presses enter or spacebar on a given element. It looks like the enter / spacebar keys are being handled by the dialog box, thus causing the default button to be clicked (cancel button). The dialog closes almost immediately after it is opened.

Here's a simplified demo:

<script type = "text / javascript">
    function Go () {
        $ ("# dialog"). text ("Are you sure?"). dialog ({
            modal: true,
            buttons: {
                Cancel: function () {
                    $ ("# dialog"). dialog ("destroy");
                },
                OK: function () {
                    $ ("# dialog"). dialog ("destroy");
                }
            }
        }); // end .dialog
    }
</script>

<input type = "button" value = "Test" onkeydown = "Go ()" />
<div title = "Dialog" style = "display: none;" id = "dialog"> </div>

If the button is given focus and then the user presses the spacebar, the dialog opens and then immediately closes. If the user hits the enter button, the dialog closes so quickly that it doesn't even blink (at least that's been my experience with Firefox 3.5.3)

How can I prevent the dialog from handling the key from the onkeydown event that caused the dialog to open?

+2


source to share


1 answer


Try turning onkeyup on if you have one. If it works, I'll give you an explanation (Busy).

Edit description: This is mainly due to the fact that the onkeydown event is not called once, it is constantly called a call while it is pressed, and since computers are running so fast (1 second is an eternity for them), it is called many times during one pressing. The solution is not to call it when it is pushed down, but to call it at the top (when you let go).



Happens all the time in electronics with switches and logic gates etc. I forgot the technical terms.

+3


source







All Articles