在Bootstrap中启动模态时如何在文本框上使用.focus()

时间:2019-01-08 21:58:26

标签: jquery html bootstrap-4

  

打开此模式时,需要使用鼠标将光标移至文本框

因此,我想在模式打开后立即在文本框上聚焦

  

Css和JS文件

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  

JavaScript代码

<script type="text/javascript">
    $(document).ready(function(){
        $('.launch-modal').click(function(){
            $('#myModal').modal({
                backdrop: 'static'
            });
        // document.form1.focushere.focus();
    }); 
    });
</script>
  

HTML代码

<body>
    <form name="form1">
        <!-- Button HTML (to Trigger Modal) -->
        <input type="button" class="btn btn-lg btn-primary launch-modal" value="Launch Demo Modal">

        <!-- Modal HTML -->
        <div id="myModal" class="modal fade">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">Confirmation Box</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                    <div class="modal-body">
                        <input type="text" id="" name="focushere">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</body>
</html>                             

1 个答案:

答案 0 :(得分:0)

从本质上讲,这是行不通的,因为未加载模式,因此没有Java字段可以保留的任何字段。

您可以修改代码以执行以下操作:

  $('#myModal').on('shown.bs.modal', function() {
    document.form1.focushere.focus();
  })

加载模态时它将运行focus()函数。

查看此答案:Twitter bootstrap - Focus on textarea inside a modal on click