Nov*_*ode 3 javascript alert twitter-bootstrap
我有以下警报div的HTML代码:
<div id="formAlert" class="alert">
<a class="close" data-dismiss="alert">×</a>
<strong>Warning!</strong> Make sure all fields are filled and try again.
</div>
Run Code Online (Sandbox Code Playgroud)
以下JavaScript:
function validateForm(){
var x=document.forms['register']['username'].value;
if (x==null || x=="") {
alert('This is an alert')
return false;
var alertDialog = document.getElementByid("formAlert");
alertDialog.style.display = "block";
}
}
Run Code Online (Sandbox Code Playgroud)
代码的问题在于,即使在调用代码之前,警报也会过早显示.我可以告诉弹出默认的JavaScript警告框时调用警报.理想情况下,在validateForm()调用时,我希望警报显示出来.validateForm()在提交表单时调用.
编辑:根据要求,这是触发validateForm()的代码:
<form name="register" action="" onSubmit="return validateForm()" method="post">
</form>
Run Code Online (Sandbox Code Playgroud)
现在我已经解决了调用它的问题,我如何隐藏div直到它被JavaScript调用,因为它已经在代码执行之前显示.
如果重新组织代码,可以将JavaScript与HTML完全分开并处理事件.这是我如何设置它:
<div id="main_area" class="row-fluid">
<div class="span10 offset1">
<div id="formAlert" class="alert hide">
<a class="close">×</a>
<strong>Warning!</strong> Make sure all fields are filled and try again.
</div>
<form name="register" action="" method="post">
<input type="text" name="username" />
<br />
<input type="submit" class="btn btn-primary" value="Submit" />
</form>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
和JS:
$(document).ready(function () {
// Run this code only when the DOM (all elements) are ready
$('form[name="register"]').on("submit", function (e) {
// Find all <form>s with the name "register", and bind a "submit" event handler
// Find the <input /> element with the name "username"
var username = $(this).find('input[name="username"]');
if ($.trim(username.val()) === "") {
// If its value is empty
e.preventDefault(); // Stop the form from submitting
$("#formAlert").slideDown(400); // Show the Alert
} else {
e.preventDefault(); // Not needed, just for demonstration
$("#formAlert").slideUp(400, function () { // Hide the Alert (if visible)
alert("Would be submitting form"); // Not needed, just for demonstration
username.val(""); // Not needed, just for demonstration
});
}
});
$(".alert").find(".close").on("click", function (e) {
// Find all elements with the "alert" class, get all descendant elements with the class "close", and bind a "click" event handler
e.stopPropagation(); // Don't allow the click to bubble up the DOM
e.preventDefault(); // Don't let any default functionality occur (in case it's a link)
$(this).closest(".alert").slideUp(400); // Hide this specific Alert
});
});
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/VzVy6/8/
实际上该data-dismiss属性<a class="close">×</a>会在单击时删除警报,因此您以后无法再显示它.因此,您可以通过手动隐藏/显示与class="close"元素关联的特定警报来执行您想要的操作,而不是使用该属性.