gpt4 book ai didi

javascript - 如何使用 Bootstrap 横幅验证文本框

转载 作者:行者123 更新时间:2023-12-01 01:03:42 25 4
gpt4 key购买 nike

我对 javascript 比较陌生,我正在尝试创建一个在文本框为空时显示的横幅。但它没有显示。如何使用 Bootstrap 横幅发出警报?

<!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>

最佳答案

编写 JS 代码时应该考虑以下几点:

  1. 如果您想要 Jquery,请始终包含 $(document).ready(function(){});等待 html 正文加载的代码。一旦加载你想要使用您的 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>

请告诉我..如果您在这方面需要任何帮助..我很乐意帮助您。谢谢

关于javascript - 如何使用 Bootstrap 横幅验证文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55821993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com