Search code examples
jqueryjquery-uijquery-dialog

jQuery UI Dialog - Enter key should equal a click


I want to be able to press "ENTER" and have the dialog execute the same thing as a submit button.

I found a similar question here: Submit jQuery UI dialog on <Enter>. I added some of the solutions to the code and nothing fixed the problem.

This is what I have so far:

The button:

<button id="myButton">Execute Tasks</button>

The dialog itself:

<div id='myDialog' title="New Task(s):">
    <p>Enter the name of the tasks you wish to execute</p>
        <form>
            <label for="name">
                <input type="text" name="name" id="name" />
            </label> 
        </form>
</div>

Inside script tags:

$('#myButton').click( function() {
    $( "#myDialog" ).dialog({
        open: function(){

            $("#myDialog").unbind('submit');
            $("#myDialog").submit(function() {
            $("#myDialog").parents('.ui-dialog').first().find('.ui-button').first().click();
            return false;
            });
        },
        buttons: {
            "Run tasks": function() { .... },
            "Cancel":function() { $(this).dialog("close"); };
        },
    });
});

Solution

  • You can bind the form submit event on dialog open. Pressing Enter within the textbox will automatically trigger the form submit.

    You can additionally Trigger the submit event upon Clicking the Run Tasks button.

    jsFiddle: http://jsfiddle.net/CodingDawg/dk7hT/

    $('#myButton').click(function () {
      $("#myDialog").dialog({
            open: function () {
                $(this).off('submit').on('submit', function () {
                    //Run tasks
                    //$(this).dialog('close'); //You can Close the dialog after running the tasks.
                    return false;
                });
            },
            buttons: {
                "Run tasks": function () {
                    $(this).find('form').submit();
                },
                    "Cancel": function () {
                    $(this).dialog("close");
                }
            }
        });
    });