简体   繁体   English

表单验证无法在jQuery中使用

[英]Form validation not working in jQuery

I'm trying a form validation in jQuery but it's not working the way I'm doing it. 我正在尝试使用jQuery进行表单验证,但是它无法按照我的方式进行。 I want the border of the input to turn red if the input area is empty when I focus out. 如果我对焦时输入区域为空,我希望输入的边框变为红色。

OR 要么

I want to add the bootstrap class called "has-danger", which turns the border and the background red-ish, if the input area is empty. 我想添加一个名为“ has-danger”的引导程序类,如果输入区域为空,它将使边框和背景变为红色。

Here's the code: 这是代码:

<fieldset class="form-group"> <br>
    <label for="name">Name</label> <br><br>
    <input type="name" class="form-control" id="name"> <br>
</fieldset>

jQuery code 1: jQuery代码1:

$("#name").blur(function() {
    if((this).val() == "" ) {
        $(this).addClass("has-danger");
    }
});

jQuery code 2: jQuery代码2:

$("#name").blur(function() {
    if((this).val() == "" ) {
        $(this).css("border", "solid 1px red");
    }

you are missing the $ just before (this) in your if statement 您在if语句中(this)之前缺少$

Note: I've added an else for when the field is filled the border gets removed 注意:我添加了一个else用于填充字段时删除border

 $("#name").blur(function() { if ($(this).val() == "") { $(this).css("border", "solid 1px red"); } else { $(this).css("border", ""); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <fieldset class="form-group"> <label for="name">Name</label> <input type="name" class="form-control" id="name"> </fieldset> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM