如何使用bootstrap横幅验证文本框

问题描述 投票:0回答:1

我是一个相对较新的JavaScript和我试图创建一个横幅,如果文本框是空的将显示。但它没有显示出来。如何使用引导横幅发出警报?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/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/3.4.0/js/bootstrap.min.js"></script>

<script type="text/javascript">

function validateForm() {
      var uname = document.getElementById("uname").value;
      if (uname == ""){
          bootstrap_alert.warning = function(message) {
            $('#alert_placeholder').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>')
        }

$('#clickme').on('click', function() {
            bootstrap_alert.warning('Please enter your name');
});
          return false;
      }
  }
</script>
</head>
<body>
Name: <input type: "text" name="uname" id="uname" />
<input type = "button" id = "clickme" value="Submit"/>
<div id = "alert_placeholder"></div>

</body>
</html>
javascript jquery html twitter-bootstrap bootstrap-modal
1个回答
1
投票

那么在编写JS代码时你应该考虑几件事:

  1. 如果您希望Jquery代码等待加载html主体,请始终包含$(document).ready(function(){});。一旦加载,你想使用你的JS代码。
  2. 另一件事你创建了一个validateform(),它永远不会从你的代码调用,你的主代码存在于该函数中。

我修改了你的代码以完美地工作

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/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/3.4.0/js/bootstrap.min.js"></script>

<script>
$( document ).ready(function() {

 $('#clickme').on('click', function() {
              bootstrap_alert('Please enter your name');
    });
      
           bootstrap_alert = function(message) {
          var uname=$("#uname").val();
      		if (uname.length==0){
            $('#alert_placeholder').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>')
        }
        else{
        $('#alert_placeholder').html('');
        }
    }
});
</script>
</head>
<body>
Name: <input type="text" name="uname" id="uname" />
<input type = "button" id = "clickme" value="Submit"/>
<div id = "alert_placeholder"></div>

</body>
</html>

让我知道..如果您在这方面需要任何帮助..我很乐意帮助您。谢谢

© www.soinside.com 2019 - 2024. All rights reserved.