javascript 在 div 容器中显示错误消息以使用 Jquery 进行验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28955472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show error messages in div container for validations using Jquery
提问by Harsh Singhi
I'm trying to show error messages in div
container using jQuery for validation.
我正在尝试div
使用 jQuery在容器中显示错误消息进行验证。
So, instead of an alert message, I want to show the error message after every control where ever the validation fails.
因此,我想在验证失败的每个控件之后显示错误消息,而不是警报消息。
if (name == '' || email == '' || mobile == '' || password == '' || cpassword == '') {
var errName = document.getElementByID("name");
errName.innerHTML += "Please enter name";
errName.innerHTML += ".red {color:red;}";
document.getElementByID("name").val = errName;
Any suggestions?
有什么建议?
回答by Yameen
A more pure jQuery approach would be as shown below
更纯的 jQuery 方法如下所示
jQuery Code
jQuery 代码
if (name == '' || email == '' || mobile == '' || password == '' || cpassword == '') {
var errName = $("#name"); //Element selector
errName.html("Please enter name"); // Put the message content inside div
errName.addClass('error-msg'); //add a class to the element
}
CSS:
CSS:
.error-msg{
background-color: #FF0000;
}
Update:
You can even combine the jQuery methods on any selector. Whenever we apply a jQuery menthod on any selector, it returns a "this" pointer, so we can combine multiple methods and apply them to a selector using a single statement. This is called "chaining"
更新:
您甚至可以在任何选择器上组合 jQuery 方法。每当我们在任何选择器上应用 jQuery 方法时,它都会返回一个“this”指针,因此我们可以组合多个方法并使用单个语句将它们应用于选择器。这称为“链式”
Read more here: http://www.w3schools.com/jquery/jquery_chaining.asp
在此处阅读更多信息:http: //www.w3schools.com/jquery/jquery_chaining.asp
if (name == '' || email == '' || mobile == '' || password == '' || cpassword == '') {
$("#name").html("Please enter name")
.addClass("error-msg"); // chained methods
}
回答by Hkidd
if (name == '' || email == '' || mobile == '' || password == '' || cpassword == '') {
var errName = $("#name"); //get element by ID
errName.append("Please enter name"); //append information to #name
errName.attr("style", "background-color: red;"); //add a style attribute
}
Edit: or you could do it like so:
编辑:或者你可以这样做:
if (name == '' || email == '' || mobile == '' || password == '' || cpassword == '') {
var errName = $("#name"); //get element by ID
errName.append("Please enter name"); //append information to #name
errName.attr("class", "alert"); //add a class to the element
}
Then you will have an .alert
class. This makes it possible for you to use this class in your CSS file.
然后你会有一.alert
节课。这使您可以在 CSS 文件中使用此类。
.alert {
background-color: #FF0000;
}