Autofocus on editable gridview field

743 Views Asked by At

How can I add the autofocus and select on the editable gridview field?

I want to make editacle field autofocus and autoselect. Here's my gridview code :

<?php Pjax::begin(); ?>
    <?= GridView::widget([
        'dataProvider'=>$dataProvider,
        'filterModel'=>$searchModel,
        'showPageSummary'=>true,
        'pjax'=>true,
        'striped'=>true,
        'hover'=>true,
        'responsiveWrap' => false,
        'panel'=>['type'=>'primary', 'heading'=>$partner_name],
        'columns'=>[
            [
                'attribute' => 'city_code',
                'label' => 'City Code',
            ],
            [
                'class'=>'kartik\grid\EditableColumn',
                'editableOptions'=>[
                   'asPopover' => false,
                   'inputType'=>\kartik\editable\Editable::INPUT_TEXT,
                ],

                'attribute'=>'amount',
                'label'=>'Amount',

            ],
        ],
    ]);

    ?>
<?php Pjax::end() ; ?>
2

There are 2 best solutions below

0
Sardor Dushamov On

Try with this JS code:

$("form input:text, form textarea").first().focus();
3
onigame On

As kartik mentions here, the Editable widget doesn't give any APIs for focus; you need to do this in javascript.

So, you need to find the popover modal's id (by default, it's called something like "<modelname>-<rowid>-<attributename>-popover"), and declare that after it is shown, the display inside ("<modelname>-<rowid>-<attributename>-disp") needs to be selected.

So, something like

<?php
  $this->registerAssetBundle(yii\web\JqueryAsset::className(), \yii\web\View::POS_HEAD); // in case you don't have jQuery set
?>
<script type="text/javascript">
$(document).ready(function() {
  for (rowid=0; rowid<10; row++) { // or some other form of iterating over your rows
    popover_id = "#city-" + rowid + "-amount-popover";  // replace city and amount with your model name and your attribute name
    $(popover_id).on('shown.bs.modal', function(event) {
      // setTimeout(function() {
      display_id = "#"+event.target.id.replace(/popover$/,'disp');
      $(display_id).select();
      // }, 10);
    });
  }
});
</script>

Note that there are two commented lines that wrap the select() call inside a timeout. Depending on your system, it might take some time between the display of the popover and the instantiation of the display (so you can focus and select on it). If that's the case, you'll need to uncomment those lines.