简体   繁体   中英

Jquery UI modal dialog, set focus on first form element

I am currently using the jquery UI modal box.

I am wondering how I can set the focus onto the first form element of the modal box when opening the dialog I think this is meant to happen by default but for some reason it is not.

How can I set the jquery ui to focus on the first form element when opening?

here is the url to the page with the modal dialog just click the Show the Dialog link on this page

You can make use of open event in jquery ui dialog and set the focus to the input id. You can do something like this.

$( ".selector" ).dialog({
   open: function(event, ui) { $('#target').focus(); }
});

Add a function bind to the shown event, then set the focus

$('#login_modal').on('shown', function () {
     $("#login_modal input").first().focus();
 });
 $('#login_modal').modal();

Thanks for the reply, in the end I had to focus using the event callback 'shown.bs.modal' to add the focus to the element.

    $('#login-modal').on('shown.bs.modal', function () {
        $("#user_session_email").focus();
    });

By default the jQuery UI Modal will give focus to the first input field in the modal.

If for some reason the first input field is not given focus, you can add the input attribute autofocus on the first input field:

<input type="text" name="date" value="" autofocus>
<input type="text" name="phone" value="">

Or if you need the second or another input field to have focus instead, then apply the input attribute autofocus to the second input field:

<input type="text" name="date" value="">
<input type="text" name="phone" value="" autofocus>

:)

try this, focus working for Jquery Modal:

setTimeout(function () { $('#cntrlId').focus(); }, 1);

I recommend using the "open" function option in the dialog construction.

See: Cannot set focus to a form field in a jQuery UI dialog on clicking a jQueryUI menu item

Add function on open dialog

$("#dialogMensaje").dialog({width: 600,
                            title: "Notificación",
                            modal: true,
                            buttons: {
                                "Enviar": function() {
                                    $(this).dialog("close");
                                }
                            },
                            open: function() {
                                setTimeout(function() {
                                    $('#txt').focus();
                                }, 420);
                            }
                        });

it takes about 460ms to completely shown the dialog box so it's better to use

setTimeout, 500

setTimeout(function(){$("#target").focus();},500);

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