Ad

How To Set Focus On Input Element In BootstrapDialog

- 1 answer

I have a BootstrapDialog with an input element and others things, and I need to set the focus on input element when BootstrapDialog appears.

Here is my code :

var instanceDialogClientDonneur = null;
...
if (instanceDialogClientDonneur == null  ) {
instanceDialogClientDonneur = new BootstrapDialog.show({
        title : titre,
        cssClass : 'lieu-dialog',
        modal : true,

        closeOnEscape : true,
        onhidden : function() {             
        instanceDialogClientDonneur =null;
            },
        message : enteteZoneRecherche + resTab +"</div>"
    });
} else {
...
}

enteteZoneRecherche is like that :

<div class="row"><div class="input-group"><span class="input-group-addon">Rechercher</span><input type="text" id="code_recherche" value="" onkeyup="completerClient(event,this.id,'clientnom','Liste des clients','remplirZonesClientAdrEnvoi','',true);" class="form-control" placeholder="Tapez un code..."></div>

and resTab :

<div id="tableauResultat" class="row" style="height:350px;overflow-y: scroll"><table class="table table-bordered table-hover"><tr><th>Code</th><th>Nom</th><th>Ville</th></tr><tr id="idTr_1106" onclick="remplirZonesClientAdrEnvoi(this.id);"><td>000006</td><td>ARSENE</td><td>Brest</td></tr><tr id="idTr_1107" onclick="remplirZonesClientAdrEnvoi(this.id);"><td>100004</td><td>ANQUETIL</td><td>BRIVES</td></tr></table></div>

I need to set focus on "code_recherche".

How can I do that ?

Ad

Answer

The official bootstrap documentation gives an example for just it http://getbootstrap.com/javascript/#modals

Example from the docs

$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').focus()
})

When using BoostrapDialog class same thing will look like

onshown: function(dialogRef){
   $('#myInput').focus();
}

So your final code will look like

if (instanceDialogClientDonneur == null  ) {
    instanceDialogClientDonneur = new BootstrapDialog.show({
        title : titre,
        cssClass : 'lieu-dialog',
        modal : true,

        closeOnEscape : true,
        onhidden : function() {             
            instanceDialogClientDonneur =null;
        },
        onshown: function(){
            $('#code_recherche').focus();
        }
        message : enteteZoneRecherche + resTab +"</div>"
    });
}
Ad
source: stackoverflow.com
Ad