I'm trying a form validation in jQuery but it's not working the way I'm doing it. 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.
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:
$("#name").blur(function() {
if((this).val() == "" ) {
$(this).addClass("has-danger");
}
});
jQuery code 2:
$("#name").blur(function() {
if((this).val() == "" ) {
$(this).css("border", "solid 1px red");
}
you are missing the $
just before (this)
in your if
statement
Note: I've added an else
for when the field is filled the border
gets removed
$("#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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.