Switch class() method is used to replace one class with another class instead of addClass() and removeClass(). We can also set duration, easing and call back arguments. I will show you how to with example.
When user clicks the search button without entering value in the text field error class will appear with transition effects. If he enters value it will rollback to default.
Example:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>search boxvalidation using switch class in jQuery</title>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<style type="text/css">
.default, input {
border: 2px solid #27659f;
}
.error {
border: 2px solid #a72b2e;
background-color: #f78080;
}
input {
width: 200px;
height: 40px;
border: 1px solid #B6BBBF;
font-size: 19px;
}
.btn {
width: 100px;
height: 50px;
background: #00BCD4;
border-style: solid;
border-color: white;
color: white;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$("#btnsearch").click(function (e) {
e.preventDefault();
var input = $(this).prev();
if (input.val() == "") {
input.switchClass("default", "error", 1200);
} else if (input.val() && input.hasClass("error")) {
input.switchClass("error", "default", 1200);
}
});
});
</script>
</head>
<body style="border: 1px solid #DED8D8; width: 500px; height: 250px; font-family: Arial;">
<h1 style="color: #E91E63">search box validation using switch class in jQuery </h1>
<input type="text"/>
<button class="btn" id="btnsearch">Search</button>
</body>
</html>
Output:
Post your comments / questions
Recent Article
- How to hide the ID field from the Django admin?
- It is impossible to add a non nullable field without specifying a default. Django error
- ImportError: cannot import name 'url' from 'django.conf.urls' - Django Error
- How to Enable Virtualization in BIOS Security Settings in Intel Processors For Android Studio?
- Dependency 'androidx.activity:activity:1.8.0' requires libraries and applications that depend on it.
- AttributeError: 'NoneType' object has no attribute 'get_text' - Python
- ModuleNotFoundError: No module named 'openpyxl' - Python
- How to get thumbnail from vimeo video URL in Python?
Related Article