Focus on field doesn't work in a bootbox callback

3.2k views Asked by At

I have a field and a "check" button that checks if the field is empty. The problem is that after the click on 'Ok' in the popup (I use bootbox), it doesn't focus the field.

I tried with document.getElementById("field").focus(); and $('#field').focus(); but it doesn't works

http://jsfiddle.net/b4y40q5h/

Thanks

3

There are 3 answers

2
kosmos On BEST ANSWER

The plugin, after click "ok", modifies the dom and you loose the focus, so you only need a timeout to achieve it: jsFiddle.

$("#btnCheck").click(function () {
    if ($('#field').val() == "")
    {
        bootbox.dialog({
            message: "empty field",
            title: 'my site',
            buttons: {
                danger: {
                    label: 'ok',
                    className: "btn-primary",
                     callback: function () {
                         setTimeout(function(){
                             $('#field').focus();
                         }, 10);
                     }
                }
            }
        });
    }
else
    alert('ok');
});
2
Guruprasad J Rao On

Write this below script:

DEMO HERE

$(document).on('hidden.bs.modal','.bootbox', function () {
   $('#field').focus();
});
0
Praveen Kumar Purushothaman On

The other way is, using a setTimeout. I did it, but it didn't work for a reason, but now it works! God only knows why!

callback: function () {
    setTimeout(function () {
        console.log("F");
        $("#field").focus();
    }, 150);
}

Fiddle: http://jsfiddle.net/praveenscience/Lcv4c5ab/1/