Class 8: Working with Forms: Validation and dynamic form updates.
Overview
This class covers:
How to validate forms using jQuery.
jQuery’s most useful events for forms.
Dynamically updating forms with jQuery.
1. Setting Up jQuery
Include jQuery in your project:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
2. Basic Form with jQuery Validation
We’ll use jQuery to validate form fields before submission.
HTML Form
<form id="signupForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<span id="userError"></span>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<span id="emailError"></span>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<span id="passError"></span>
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function(){
$("#signupForm").submit(function(event){
let valid = true;
let username = $("#username").val();
if(username.length < 3){
$("#userError").text("Username must be at least 3 characters.");
valid = false;
} else {
$("#userError").text("");
}
let email = $("#email").val();
if(!email.includes("@")){
$("#emailError").text("Enter a valid email.");
valid = false;
} else {
$("#emailError").text("");
}
let password = $("#password").val();
if(password.length < 6){
$("#passError").text("Password must be at least 6 characters.");
valid = false;
} else {
$("#passError").text("");
}
if(!valid) event.preventDefault();
});
});
</script>
Prevents form submission if validation fails.
Displays error messages dynamically.
3. Most Useful jQuery Form Events
1. focus() – Highlighting Fields on Focus
$("input").focus(function(){
$(this).css("background-color", "#f0f8ff");
});
Changes background color when an input field is selected.
2. blur() – Validating on Leaving the Field
$("#email").blur(function(){
let email = $(this).val();
if (!email.includes("@")) {
$("#emailError").text("Invalid email format.");
} else {
$("#emailError").text("");
}
});
Checks email format when leaving the input field.
3. change() – Detecting Dropdown Changes
$("#accountType").change(function(){
let selected = $(this).val();
alert("You selected: " + selected);
});
Alerts the user when they select an option.
4. keyup() – Live Character Counter
$("#message").keyup(function(){
$("#charCount").text($(this).val().length + "/200 characters used");
});
Updates character count in real-time.
5. keypress() – Detecting Keystrokes
$("#username").keypress(function(){
$("#userError").text("Typing...");
});
Displays a message while typing.
6. bind() – Attach Multiple Events
$("#password").bind("focus blur", function(event){
if(event.type === "focus"){
$(this).css("border", "2px solid blue");
} else {
$(this).css("border", "1px solid gray");
}
});
Adds multiple event listeners in one function.
4. Dynamic Form Updates with jQuery
Show/Hide Fields Based on Selection
<form>
<label>Account Type:</label>
<select id="accountType">
<option value="user">User</option>
<option value="business">Business</option>
</select>
<div id="businessField" style="display:none;">
<label>Business Name:</label>
<input type="text" id="businessName">
</div>
</form>
<script>
$("#accountType").change(function(){
if($(this).val() === "business"){
$("#businessField").show();
} else {
$("#businessField").hide();
}
});
</script>
Shows business name field only if “Business” is selected.
5. Form Submission Using AJAX
Instead of refreshing the page, jQuery can send form data asynchronously.
<form id="ajaxForm">
<input type="text" id="name" placeholder="Your Name">
<input type="email" id="email" placeholder="Your Email">
<button type="submit">Send</button>
</form>
<script>
$("#ajaxForm").submit(function(event){
event.preventDefault();
let formData = {
name: $("#name").val(),
email: $("#email").val()
};
$.ajax({
type: "POST",
url: "submit.php",
data: formData,
success: function(response){
alert("Form submitted successfully!");
},
error: function(){
alert("Error submitting form.");
}
});
});
</script>
Sends form data to the server without refreshing the page.
Conclusion
By the end of this class, you’ll be able to:
Validate forms using jQuery.
Use jQuery events for real-time updates.
Submit forms using AJAX.
Would you like additional examples or explanations?