Position focus on a modal window field - JavaScript and Asp.net MVC

1

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 in common have the field Description (Description). I need to make sure that whenever the modal window is opened, the focus of the cursor is directed to the Description field. This is using javascript. In my case is it 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>*@
}

    
asked by anonymous 11.05.2018 / 00:26

1 answer

2

If you use Bootstrap , put the configuration in the shown.bs.modal , which will provide 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();
});
    
11.05.2018 / 01:52