Position focus in a field of a modal window - Javascript and Asp.net MVC

Asked

Viewed 1,545 times

2

I have a view model that has a block that opens modal windows for CRUD actions. I have 4 partial viewls: create, delete, Details and Edit ... All have the Description (Description) field in common. I need to make sure that whenever the modal window opens, the cursor focus is directed to the Description field. This is using javascript. In my case it’s possible?

Thank you!

Modal window block Index:

<a id="btnNovo" asp-action="Create" data-modal="" class="btn btn-outline btn-default new" data-toggle="tooltip"
         data-original-title="Cadastrar Novo" data-container="body">
        <span title="Cadastrar Novo" class="icon wb-plus"></span> Cadastrar Novo
    </a>

    <div class="modal fade modal-primary" id="modalPessoaSituacao" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
        <div class="modal-dialog" style="width: 45%; height: 500px;">
            <div class="modal-content">
                <div id="contentModal"></div>
            </div>
        </div>
    </div>
    
     <script src="~/js/cadastros/pessoaSituacao/pessoaSituacao.js"></script>

My JS Configuration File:

$(document).ready(function () {
    $.ajaxSetup({ cache: false });
    // busca los elementos el atributo data-modal y le suscribe el evento click
    $('a[data-modal]').on('click', function (e) {
        // Abre la ventana modal con el formulario solicitado 
        openmodal(this.href);
        return false;
    });
    $('#modalPessoaSituacao').on('hidden.bs.modal', function () {
        $('#contentModal').html('');
    })
});
function openmodal(url) {
    // Hace una petición get y carga el formulario en la ventana modal
    $('#contentModal').load(url, function () {
        $('#modalPessoaSituacao').modal({
            keyboard: true
        }, 'show');
        // Suscribe el evento submit
        bindForm(this);
    });
}
function bindForm(dialog) {
    // Suscribe el formulario en la ventana modal con el evento submit
    $('form', dialog).submit(function () {
        if ($(this).valid()) {
            // Realiza una petición ajax
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    // Si la petición es satisfactoria, se recarga la página actual
                    if (result.success) {
                        window.location = window.location;
                        window.location.reload(); //Ajuda na exclusao, atualizando o grid

                    } else {
                        $('#contentModal').html(result);
                        bindForm();
                    }
                }
            });
            return false;
        } else {
            return false;
        }
    });
}

My Partialview Create:

@using SistemaComercial.Domain.ValueObjects
@model SistemaComercial.Application.ViewModels.PessoaSituacao.PessoaSituacaoViewModel
@{
    ViewData["Title"] = "Cadastrar Situação de Pessoa";
}

<div>
    <form asp-action="Create">
        @Html.AntiForgeryToken()

        <div class="modal-shadow">
            <div class="modal-header modal-header-primary">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title text-center"> @ViewData["Title"] </h4>
            </div>
            <div class="form-horizontal">
                <div id="validationSummary" class="text-center">
                    <vc:summary />
                </div>
                <div class="panel-body">
                    <div class="form-group">
                        <label asp-for="Id" class="col-md-3 control-label"></label>
                        <div class="col-md-2">
                            <input asp-for="Id" class="form-control" />
                            <span asp-validation-for="Id" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label asp-for="Descricao" class="col-md-3 control-label"></label>
                        <div class="col-md-7">
                            <input asp-for="Descricao" class="form-control text-uppercase" />
                            <span asp-validation-for="Descricao" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label asp-for="PessoaTipo" class="col-md-3 control-label"></label>
                        <div class="col-md-3">
                            <select asp-for="PessoaTipo" asp-items="Model.PessoasTipos" data-toggle="dropdown" data-plugin="selectpicker" title="Selecione uma opção" class=" form-control show-tick show-menu-arrow"></select>
                            <span asp-validation-for="PessoaTipo" class="text-danger"></span>
                        </div>
                        <div class="col-md-5">
                            <div class="checkbox-custom checkbox-primary">
                                <label asp-for="PadraoSistema"></label>
                                <input asp-for="PadraoSistema" disabled />
                            </div>
                            <span asp-validation-for="PadraoSistema" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button id="btnSalvar" type="submit" class="btn btn-primary"><i class="icon wb-check"></i> Salvar </button>
                        <a class="btn btn-danger" data-dismiss="modal">
                            <span title="Fechar" class="icon wb-close"></span> Fechar
                        </a>
                    </div>
                </div>
            </div>
        </div>

    </form>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    @*<script type="text/javascript">
            $(function () {
                //allow validation framework to parse DOM
                $.validator.unobtrusive.parse('form');
            });
        </script>*@
}

inserir a descrição da imagem aqui

  • What is the CSS you are using?

  • 1

    Hi Virgilio!! I’m currently using bootstrap classes from a framework called Remark. All I did was create a JS archive as I mentioned on the topic.

  • I put an example!

1 answer

3


If used Bootstrap put the settings in the event Shown.bs.modal, which will provide the focus in some element of modal when it is visible to the user, see example below:

$('#exampleModalLong').on('shown.bs.modal', function(event) {
  $("#t1").focus();
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <input type="text" id="t1" class="form-control" focus />
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
  Launch demo modal
</button>

in your specific case just add:

$('#modalPessoaSituacao').on('shown.bs.modal', function () {
    $('#Descricao').focus();
});
  • The modal opening process is done differently... Function openmodal(url) { $('#contentModal'). load(url, Function() { $('#modalPessoa').modal({ Keyboard: true }, show'); bindForm(this); }); }

  • Now I’m in doubt...

  • @Jalberromano doesn’t matter! man just add the event as a given example, I’ve even done editing and passed in your case ...!!! the way you open the modal, no matter, it just needs to have the event, as demonstrated in the answer!

  • The only difference is that you need to load before showing the modal !!! @Jalberromano has to change the loading order

  • I got it... It worked like this: Function openmodal(url) ː $('#contentModal'). load(url, Function() { $('#modalPessoaSituacao').modal({ Keyboard: true }, 'show'); $('#modalPessoaSituacao').on('Shown.bs.modal', Function(Event) { $("#txtDescription").Focus() }); bindForm(this); }); }

  • 1

    Thank you @Virgilio Novic

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.