在模态中捕获.on('更改)文本框

时间:2017-06-07 18:55:46

标签: jquery twitter-bootstrap bootstrap-modal

我有一个包含文本框的模态。我想让用户只需输入框,当输入符合要求(长度为4)时,调用一个函数。问题是.on('更改')函数似乎仅在您单击模态中的某个位置时处理,或者关闭模态。

我正在使用bootstrap 3.3.7和jquery 3.1.1

$('#signInModal').modal('show');

$('#signInModal-passwordText').on('change', function() {
  //some diagnostic stuff
  $('#signInModal-failedSpan').show();
  $('#signInModal-failedSpan').html($(this).val());
  if ($(this).val().length == 4) {
    //alert('4');
    signIn($(this).val());
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<div class="modal fade" tabindex="-1" role="dialog" id="signInModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Sign In</h4>
      </div>
      <div class="modal-body">
        <input id="signInModal-passwordText" type="password" class="form-control" />
        <span class="alert alert-danger" style="display: none;" role="alert" id="signInModal-failedSpan">Failed!</span>
      </div>
      <div class="modal-footer">
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

2 个答案:

答案 0 :(得分:3)

我会使用onkeyup,因为更改需要在许多浏览器中模糊才能触发:

Diffrence between keyup keydown keypress and input events

function signIn(val) { alert(val)}
$('#signInModal').modal('show');

$('#signInModal-passwordText').on('keyup', function() {
  //some diagnostic stuff
  $('#signInModal-failedSpan').show();
  $('#signInModal-failedSpan').html($(this).val());
  if ($(this).val().length == 4) {
    signIn($(this).val());
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<div class="modal fade" tabindex="-1" role="dialog" id="signInModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Sign In</h4>
      </div>
      <div class="modal-body">
        <input id="signInModal-passwordText" type="password" class="form-control" />
        <span class="alert alert-danger" style="display: none;" role="alert" id="signInModal-failedSpan">Failed!</span>
      </div>
      <div class="modal-footer">
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

答案 1 :(得分:0)

我知道这个问题有点老了,但这可能会对其他人有所帮助。

您可能已经更改了这一行:

$('#signInModal-passwordText').on('change', function() {

收件人:

$('.modal').on('change', '#signInModal-passwordText', function() {