简体   繁体   中英

Unable to get focus on Textbox when bootstrap modal popup opens

Hii I want to get focus on input textbox when the bootstrap modal popup opens

<div class="modal fade nopading" id="myModalpop" role="dialog">
    <div class="model-area">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-head">
                <a class="navbar-brand" href="index.html"><img src="~/Content/images/logo.png" alt="Ova" style="float: left; padding-top: 10px;"></a>
                <form class="form-inline md-form form-sm mt-0" style="text-align: center;" method="get" action="@Url.Action("Review", "Product")">
                    <a href"#"><i class="fa fa-search" aria-hidden="true"></i></a>
                    <input name="id" class="form-contro form-control-sm ml-3 w-75 wow fadeInRight animated" id="txtsearch"  type="text" placeholder="Search" aria-label="Search">
                </form>
                <button type="button" class="close" data-dismiss="modal">&times;</button>

            </div>
            <div class="modal-body" style="padding: 0px;">
                @*<p class="links_p wow fadeInRight animated">QUICK LINKS</p>*@

            </div>

        </div>
    </div>

</div><!-- end navbar-cell -->

I have applied javascript

<script type="text/javascript">
$(document).ready(function () {

    $('#myModalpop').on('show.bs.modal', function () {

        $('#txtsearch').focus;
        //$(this).find('#txtsearch').focus();
     });
});
</script>

Focus on textbox

Edit:

<div class="model-area">

'show.bs.modal'

change to

<div class="modal-dialog">

'shown.bs.modal'

Notice model and modal


Did you missed the bracket?

$('#txtsearch').focus();

使用选定的弹出ID调用。

$('#myModalpop #txtsearch').focus();

You have two solutions to solve this issue

first one is using setTimeout function to set focus your textbox within 'show.bs.modal' event because this event is fired before model shown as following

$(function () {
    $('#myModalpop').on('show.bs.modal', function () {
          setTimeout(function(){ $('#txtsearch').focus(); }, 300);         
     });
});

second solution is using 'shown.bs.modal' event which fired after modal shown but you should remove class fade from you model as following:

$(function () {
    $('#myModalpop').on('shown.bs.modal', function () { 
        $('#txtsearch').focus();
     });
});

For me, setTimeout(function(){ $("#modal_name").focus(); }, 500); is worked!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM