根据用户输入弹出一个模态

时间:2019-02-15 22:08:51

标签: javascript html input bootstrap-4 bootstrap-modal

我有用户输入表单,用户可以在其中输入数字,如果数字小于零或大于4,则会弹出javascript警报。我正在尝试用引导程序模式替换我的javascript警报。

我已经将此boostrap模式添加到我的html代码中,当前可以使用按钮将其弹出。但是正如我说的,我想基于无效的用户输入(小于零或大于4)而不是单击按钮来触发模式。

<input type="number" class="form-control" id=22 onkeyup="a(this)">
<button type="button" class="btn btn-primary" data-toggle="modal" datatarget=".bd-example-modal-sm">Small modal</button>
<div class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog"aria-labelledby="mySmallModalLabel" aria-hidden="true" id="modal">
<div class="modal-dialog modal-sm">
    <div class="modal-content">
        ...
    </div>
</div>
</div>


 function a(c){
    var valueStr = c.value;
    var value = parseFloat(valueStr)
    if ((event.keyCode||event.which) >= 48 && (event.keyCode||event.which) <= 90 ){
        if (value <= 0 && value >= 4) {
            alert("Value must be between 0 and 4");
        }

    }
}

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">

  <input type="number" class="form-control" id="22" onkeyup="a()" data-target="#myModal">
  <!-- Button to Open the Modal -->

  <!-- The Modal -->
  <div class="modal" id="myModal">
    <div class="modal-dialog">
      <div class="modal-content">

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

        <!-- Modal body -->
        <div class="modal-body">
          <h1>Value must be between 0 and 4</h1>
        </div>

        <!-- Modal footer -->
        <div class="modal-footer">
          <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
        </div>

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

</div>
<script>
 function a(){
    var x = document.getElementById("22");
    console.log(x.value);
    if(x.value>=4 || x.value<=0){
    $('#myModal').modal('show');
    }
}
</script>
</body>
</html>