我正在使用Bootstrap 3.2.0。我想验证一个表单。我已经可以在用户名为空的情况下验证我的表单,因此警报会显示但会立即消失,因此用户将无法阅读该消息。我不知道如何设定一个自动消失的时间,或者不关闭它就把它留在那里。
这是我的HTML代码:
<div class="container">
<div class="row">
<div class="col-lg-6">
<div class="well bs-component">
<form class="form-horizontal" name="login" method="post">
<fieldset>
<legend>L Torres Goldsmith</legend>
<div class="form-group">
<label for="inputEmail" class="col-lg-2 control-label">User:</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputEmail" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" class="form-control" id="inputPassword" name="password" placeholder="Password">
<div class="checkbox">
<label>
<input type="checkbox"> Keep me signed in
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="submit" class="btn btn-primary" onclick="validateForm();">Submit</button>
<button class="btn btn-default">Cancel</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
<div class="col-lg-6" id="wronguser">
</div>
</div>
</div>
这是我的javascript代码:
<script type="text/javascript">
function validateForm() {
var user = document.forms["login"]["username"].value;
var html = "";
if( user.trim() == "" )
{
document.getElementById("wronguser").style.display = "block";
html = "<div class=\"alert alert-dismissable alert-warning\" id=\"wronguser\">";
html += "<button type='button' class='close' data-dismiss='alert'>×</button> ";
html += "<h4>Warning!</h4>";
html += "<p>Something went wrong.</p>";
document.getElementById("wronguser").innerHTML = html;
}
}
</script>
有谁知道如何解决我的问题?
答案 0 :(得分:1)
实际上,当您单击“提交”按钮时,您的页面将重新加载。将您的javascript函数更改为return
一些布尔值,如下所示:
<script type="text/javascript">
function validateForm() {
var user = document.forms["login"]["username"].value;
if( user.trim() == "" )
{
var html = "";
document.getElementById("wronguser").style.display = "block";
html = "<div class=\"alert alert-dismissable alert-warning\" id=\"wronguser\">";
html += "<button type='button' class='close' data-dismiss='alert'>×</button> ";
html += "<h4>Warning!</h4>";
html += "<p>Something went wrong.</p>";
document.getElementById("wronguser").innerHTML = html;
return false;
}
return true;
}
</script>
并将onclick事件中return
之前的validateForm()
添加到提交按钮中。
<button type="submit" class="btn btn-primary" onclick="return validateForm();">Submit</button>
仅供参考:如果您将类型从submit
更改为type="button"
;您的页面无法重新加载。