简体   繁体   中英

How to stop enter key from submitting form when input area in jQuery ui form dialog is highlighted? (sample code)

See code below for working demo. A jQuery UI modal dialog box is opened, and the user is asked to enter a password. If the submit button is highlighted, everything works just fine. If, however, the input area is still highlighted, then the page appears to reload, and the URL in the browser is changed to example.com?confirm_password=asdfasdf# .

I suspect this is because I have a form embedded in the dialog box, but this is based on a jQuery example.

How can I fix this so that pressing the enter key with the text input box highlighted is equivalent to clicking on submit?

<html>
<head>
    <title>Problem Demo</title>
    <link href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" rel="stylesheet" type="text/css">
    <script src="http://code.jquery.com/jquery-1.7.min.js"></script>
    <script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#myDialog').dialog({
                autoOpen: false,
                modal: true,
                buttons: {
                    "Submit": function() {
                        $(this).dialog('close');
                    },
                    Cancel: function() {
                        $(this).dialog('close');
                    }
                }
            });

            $('#openMyDialog').click(function() {
                $('#myDialog').dialog('open');          
            });
        });
    </script>
</head>
<body>
    <a id="openMyDialog" href="#">Open Dialog</a>
    <div id="myDialog">
        <p style="text-align: left;">Please enter your password.</p> 
        <form>
            <fieldset>
                <label for="confirm_password">Password</label>
                <input type="password" name="confirm_password" id="confirm_password" value="" />
            </fieldset>
        </form>
    </div>
</body>
</html>

It is look like submit function is only working with button key(button submit function being called only on button click ).

you should explicitly bind your form using

$('yourformselector').submit(function(){
          $(this).dialog('close');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM