Target an element in Bootstrap modal

2020-04-15 05:36发布


I wrote this code so when the user is at the password textbox, he/she can press enter to log in. However, I think because it is in the bootstrap modal so I couldn't target it with jQuery selector. Any idea?

Here is the HTML:

                    <!-- Modal content -->
                    <div class="modal-content">

                      <!-- header -->
                      <div class="modal-header"> 
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Login</h4>
                      </div>

                      <!-- body -->
                      <div class="modal-body text-center" >
                          <input class='form-control' type="text" id="userName" placeholder="Username" ng-model='username'>
                          <input class='form-control' type="password" id="password" placeholder="Password" ng-model='password'>

                      <div class="modal-footer">
                        <button type="button" class="btn btn-default" id ="loginButton" ng-click="goToAdminPanel()">Login</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal" id="closeButton">Close</button>
                      </div>

                    </div>

                 </div>
                </div>
           </div>


And the jQuery

 $("input#password").keyup(function(event){
if(event.keyCode == 13){
    $("#loginButton").click();
    console.log('This is enter');
}});

2条回答
时光不老,我们不散
2楼-- · 2020-04-15 06:24

You have two ways to solve this :

  • event delegation
  • use the browser default behavior with forms and submit actions

I would suggest the latter as it doesn't need javascript and it would have better support with mobile browser for instance.

First, your code does not show a <form> tag although you use <input>, this looks like a bad practice.

Next, if your login button was the type submit instead of button, the enter key would automatically submit the parent form when pressed while a field is focused.

Then, you could either handle the submit event or not, depending on your use case.

查看更多
Bombasti
3楼-- · 2020-04-15 06:28

that should work.. unless you are generating the form after the script has ran.

try :-

$(document).on('keyup', 'input#password', function(event){
   if(event.keyCode == 13){
       $("#loginButton").click();
       console.log('This is enter');
   }
});

or wire the event inside document.ready

$(function(){
   $("input#password").keyup(function(event){
      if(event.keyCode == 13){
        $("#loginButton").click();
        console.log('This is enter');
      }
   });
});
查看更多
登录 后发表回答