jQuery Form Methods — Complete Guide to .val(), .serialize(), and Form Events
In this tutorial, you will learn about jquery form methods. We cover key concepts, practical examples, and best practices to help you master this topic.
jQuery form methods simplify reading input values, serializing form data, and handling form events, providing a consistent API for text inputs, selects, checkboxes, radio buttons, and textareas.
What You'll Learn
- Using .val() to read and set form values
- Serializing forms with .serialize() and .serializeArray()
- Handling form submission and input events
- Managing select elements and options
- Form validation patterns
Why It Matters
Forms are the primary way users submit data. jQuery's form methods normalize browser differences and provide concise APIs for common form tasks like getting values, building query strings, and responding to input changes.
Real-World Use
A contact form that validates inputs on blur, serializes data on submit, sends it via AJAX, and shows success/error messages — all driven by jQuery form methods without page reloads.
Form Data Flow
flowchart LR
A[User Input] --> B[.val() reads]
B --> C[.serialize()]
C --> D[Query String]
D --> E[AJAX Submit]
F[Server Response] --> G[.val() sets]
style B fill:#e6f3ff,stroke:#4a90d9,stroke-width:2px
.val() — Getting and Setting Values
// Get current value
var name = $('#name-input').val();
var email = $('input[type="email"]').val();
// Set value
$('#name-input').val('Alice Johnson');
$('#email-input').val('alice@example.com');
// Set with callback
$('input[type="text"]').val(function(index, currentValue) {
return currentValue.trim();
});
// Select single select
$('#country').val('US');
// Multi-select
$('#tags').val(['javascript', 'jquery', 'html']);
// Checkbox/radio (checked state)
$('#agree').prop('checked', true);
Expected output: .val() returns the current value of the first element in the set. Setting .val('new') updates all matched elements.
.serialize() — Encode Form Data
// Serialize entire form to query string
var formData = $('#myForm').serialize();
console.log(formData);
// Output: name=Alice&email=alice%40example.com&country=US
// Send via AJAX
$.post('/api/submit', $('#myForm').serialize(), function(response) {
console.log('Server response:', response);
});
// .serialize() includes:
// - All successful form controls (with name attribute)
// - Text inputs, textareas, selects, checkboxes (if checked)
// - Radio buttons (if selected)
.serializeArray() — Form Data as Array
var dataArray = $('#myForm').serializeArray();
console.log(dataArray);
// Output:
// [
// { name: 'name', value: 'Alice' },
// { name: 'email', value: 'alice@example.com' },
// { name: 'country', value: 'US' }
// ]
// Convert to object
var formObj = {};
$.each($('#myForm').serializeArray(), function(i, field) {
formObj[field.name] = field.value;
});
console.log(formObj);
// Output: { name: 'Alice', email: 'alice@example.com', country: 'US' }
Form Submission
// Intercept form submission
$('#myForm').on('submit', function(event) {
event.preventDefault(); // Stop browser from reloading
var $form = $(this);
// Validate
var isValid = validateForm($form);
if (!isValid) return;
// Submit via AJAX
$.ajax({
url: $form.attr('action'),
method: $form.attr('method') || 'POST',
data: $form.serialize(),
success: function(response) {
$('#result').text('Success!').addClass('alert-success');
},
error: function() {
$('#result').text('Error!').addClass('alert-error');
}
});
});
Input Event Handling
// Real-time input tracking
$('#search-input').on('input', function() {
var query = $(this).val();
if (query.length >= 3) {
performSearch(query);
}
});
// Change event (fires when value changes and focus leaves)
$('#country').on('change', function() {
var selected = $(this).val();
loadStates(selected);
});
// Focus and blur
$('input').on('focus', function() {
$(this).addClass('focused');
}).on('blur', function() {
$(this).removeClass('focused');
validateField($(this));
});
// Key events
$('#username').on('keyup', function(e) {
if (e.keyCode === 13) { // Enter key
$('#submit-btn').click();
}
});
Managing Select Elements
// Populate a select dynamically
var countries = [
{ code: 'US', name: 'United States' },
{ code: 'CA', name: 'Canada' },
{ code: 'MX', name: 'Mexico' }
];
var $select = $('#country-select');
$select.empty(); // Clear existing options
$select.append('<option value="">Select a country...</option>');
$.each(countries, function(i, country) {
$select.append(
$('<option>', { value: country.code, text: country.name })
);
});
// Get selected text (not value)
var selectedText = $('#country-select option:selected').text();
// Enable/disable options
$('#country-select option[value="MX"]').prop('disabled', true);
Checkbox and Radio Form Patterns
// Get all checked checkbox values
var selectedInterests = [];
$('input[name="interests"]:checked').each(function() {
selectedInterests.push($(this).val());
});
// Toggle all checkboxes
$('#select-all').on('change', function() {
var isChecked = $(this).prop('checked');
$('input[name="items"]').prop('checked', isChecked);
});
// Radio button change
$('input[name="shipping"]').on('change', function() {
var selectedMethod = $(this).val();
updateShippingCost(selectedMethod);
});
Form Validation Patterns
function validateField($field) {
var value = $field.val().trim();
var name = $field.attr('name');
var $error = $field.next('.error-message');
// Clear previous error
$field.removeClass('valid invalid');
$error.text('');
if ($field.prop('required') && !value) {
$field.addClass('invalid');
$error.text(name + ' is required');
return false;
}
if (name === 'email' && value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
$field.addClass('invalid');
$error.text('Invalid email format');
return false;
}
$field.addClass('valid');
return true;
}
// Validate all fields on submit
$('#form').on('submit', function(e) {
e.preventDefault();
var allValid = true;
$(this).find('input, select, textarea').each(function() {
if (!validateField($(this))) {
allValid = false;
}
});
if (allValid) {
// Submit
}
});
Common Mistakes
Using .val() on non-form elements -
.val()only works on form elements (input, select, textarea, button). For other elements, use.text()or.html().Forgetting .serialize() only includes successful controls - Disabled fields and unchecked checkboxes are not included. Add hidden inputs for unchecked boolean values.
Not trimming input values - User input often includes leading/trailing whitespace. Always
.trim()before validation or submission.Relying on .val() default value vs current value -
.val()always returns the current value, not the defaultValue attribute. For the initial value, use.prop('defaultValue').Serializing forms with file inputs -
.serialize()does not include file data. Use FormData for file uploads:var formData = new FormData(this).
Practice Questions
- What does .serialize() return?
- How do you get the checked values from a group of checkboxes?
- What is the difference between .serialize() and .serializeArray()?
- Why do you call event.preventDefault() in a submit handler?
- How do you populate a select element dynamically?
Challenge: Build a dynamic form with dependent selects (Country -> State -> City). When the user selects a country, populate the state select with that country's states. When a state is selected, populate the city select. Use .val(), .empty(), and .append().
FAQ
Mini Project
Build a multi-step checkout form with four steps (Cart, Shipping, Payment, Review). Each step validates before proceeding. On the final step, serialize all form data and display it for review before submitting via AJAX.
What's Next
Forms submit data, but data often comes from servers. Learn how jQuery AJAX methods send and receive data without page reloads.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro