0
# Form Handling
1
2
Form serialization, validation support, and input value management. Provides comprehensive form processing capabilities for web applications.
3
4
## Capabilities
5
6
### Form Serialization
7
8
Convert form data to various formats for submission or processing.
9
10
```javascript { .api }
11
/**
12
* Serialize form data to URL-encoded string
13
* @returns String of serialized form data
14
*/
15
$.fn.serialize();
16
17
/**
18
* Serialize form data to array of name/value objects
19
* @returns Array of {name, value} objects
20
*/
21
$.fn.serializeArray();
22
```
23
24
**Usage Examples:**
25
26
```javascript
27
// URL-encoded serialization
28
const formData = $('#myForm').serialize();
29
// Result: "name=John&email=john%40example.com&age=30"
30
31
// Array serialization
32
const formArray = $('#myForm').serializeArray();
33
// Result: [
34
// {name: 'name', value: 'John'},
35
// {name: 'email', value: 'john@example.com'},
36
// {name: 'age', value: '30'}
37
// ]
38
39
// Submit form data via Ajax
40
$('#contactForm').on('submit', function(e) {
41
e.preventDefault();
42
$.post('/api/contact', $(this).serialize(), function(response) {
43
console.log('Form submitted:', response);
44
});
45
});
46
```
47
48
### Form Values
49
50
Get and set form input values with type-specific handling.
51
52
```javascript { .api }
53
/**
54
* Get or set form element values
55
* @param value - Value to set (if provided)
56
* @returns Current value (if getting) or collection (if setting)
57
*/
58
$.fn.val(value);
59
```
60
61
**Usage Examples:**
62
63
```javascript
64
// Get values
65
const name = $('#name').val();
66
const email = $('#email').val();
67
68
// Set values
69
$('#name').val('John Doe');
70
$('#age').val(25);
71
72
// Handle different input types
73
$('#checkbox').val(['option1', 'option3']); // Check multiple checkboxes
74
$('#select-multiple').val(['value1', 'value2']); // Select multiple options
75
76
// Clear form values
77
$('#myForm input, #myForm textarea').val('');
78
$('#myForm select').val(null);
79
80
// Get selected values from multi-select
81
const selectedOptions = $('#multiSelect').val();
82
// Returns array: ['value1', 'value2']
83
```
84
85
### Form Submission
86
87
Handle form submission events with validation and processing.
88
89
```javascript { .api }
90
/**
91
* Bind form submission event handler
92
* @param callback - Function to call on form submit
93
* @returns Original collection
94
*/
95
$.fn.submit(callback);
96
```
97
98
**Usage Examples:**
99
100
```javascript
101
// Basic form submission
102
$('#myForm').submit(function(e) {
103
e.preventDefault();
104
console.log('Form submitted');
105
});
106
107
// Form validation before submission
108
$('#registrationForm').submit(function(e) {
109
e.preventDefault();
110
111
const name = $('#name').val().trim();
112
const email = $('#email').val().trim();
113
114
if (!name) {
115
alert('Name is required');
116
return false;
117
}
118
119
if (!email || !email.includes('@')) {
120
alert('Valid email is required');
121
return false;
122
}
123
124
// Submit valid form
125
$.post('/register', $(this).serialize(), function(response) {
126
window.location = '/welcome';
127
});
128
});
129
130
// Programmatically trigger submission
131
$('#submitButton').click(function() {
132
$('#myForm').submit();
133
});
134
```
135
136
### Form Validation Helpers
137
138
Utility patterns for common form validation scenarios.
139
140
```javascript
141
// Email validation
142
function isValidEmail(email) {
143
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
144
}
145
146
// Required field validation
147
function validateRequired(selector, message) {
148
const value = $(selector).val().trim();
149
if (!value) {
150
showError(selector, message);
151
return false;
152
}
153
return true;
154
}
155
156
// Show validation errors
157
function showError(selector, message) {
158
$(selector)
159
.addClass('error')
160
.siblings('.error-message')
161
.text(message)
162
.show();
163
}
164
165
// Clear validation errors
166
function clearErrors() {
167
$('.error').removeClass('error');
168
$('.error-message').hide();
169
}
170
171
// Complete validation example
172
$('#loginForm').submit(function(e) {
173
e.preventDefault();
174
clearErrors();
175
176
let isValid = true;
177
178
isValid &= validateRequired('#username', 'Username is required');
179
isValid &= validateRequired('#password', 'Password is required');
180
181
const email = $('#email').val();
182
if (email && !isValidEmail(email)) {
183
showError('#email', 'Please enter a valid email');
184
isValid = false;
185
}
186
187
if (isValid) {
188
submitForm($(this));
189
}
190
});
191
```
192
193
### Dynamic Form Handling
194
195
Working with dynamically generated form elements.
196
197
```javascript
198
// Handle dynamically added fields
199
$('#addField').click(function() {
200
const fieldCount = $('.dynamic-field').length;
201
const newField = $(`
202
<div class="dynamic-field">
203
<input type="text" name="field_${fieldCount}" placeholder="Field ${fieldCount + 1}">
204
<button type="button" class="remove-field">Remove</button>
205
</div>
206
`);
207
208
$('#dynamicFields').append(newField);
209
});
210
211
// Remove dynamic fields
212
$(document).on('click', '.remove-field', function() {
213
$(this).closest('.dynamic-field').remove();
214
});
215
216
// Serialize dynamic form
217
$('#dynamicForm').submit(function(e) {
218
e.preventDefault();
219
220
const formData = {};
221
$(this).serializeArray().forEach(function(field) {
222
formData[field.name] = field.value;
223
});
224
225
console.log('Dynamic form data:', formData);
226
});
227
```
228
229
### File Upload Handling
230
231
Working with file inputs and uploads.
232
233
```javascript
234
// Handle file selection
235
$('#fileInput').on('change', function() {
236
const files = this.files;
237
if (files.length > 0) {
238
console.log('Selected file:', files[0].name);
239
$('#fileName').text(files[0].name);
240
}
241
});
242
243
// Upload with FormData
244
$('#uploadForm').submit(function(e) {
245
e.preventDefault();
246
247
const formData = new FormData(this);
248
249
$.ajax({
250
url: '/upload',
251
type: 'POST',
252
data: formData,
253
processData: false,
254
contentType: false,
255
success: function(response) {
256
console.log('Upload successful:', response);
257
},
258
error: function() {
259
console.log('Upload failed');
260
}
261
});
262
});
263
264
// Drag and drop file upload
265
$('#dropZone')
266
.on('dragover', function(e) {
267
e.preventDefault();
268
$(this).addClass('drag-over');
269
})
270
.on('dragleave', function() {
271
$(this).removeClass('drag-over');
272
})
273
.on('drop', function(e) {
274
e.preventDefault();
275
$(this).removeClass('drag-over');
276
277
const files = e.originalEvent.dataTransfer.files;
278
handleFileUpload(files);
279
});
280
```
281
282
### Form State Management
283
284
Tracking form changes and states.
285
286
```javascript
287
// Track form changes
288
let formChanged = false;
289
290
$('#myForm').on('input change', 'input, textarea, select', function() {
291
formChanged = true;
292
$('#saveStatus').text('Unsaved changes');
293
});
294
295
// Warn about unsaved changes
296
$(window).on('beforeunload', function() {
297
if (formChanged) {
298
return 'You have unsaved changes. Are you sure you want to leave?';
299
}
300
});
301
302
// Auto-save functionality
303
let saveTimeout;
304
$('#autoSaveForm').on('input change', 'input, textarea, select', function() {
305
clearTimeout(saveTimeout);
306
saveTimeout = setTimeout(function() {
307
autoSave();
308
}, 2000); // Save after 2 seconds of inactivity
309
});
310
311
function autoSave() {
312
const formData = $('#autoSaveForm').serialize();
313
$.post('/autosave', formData, function() {
314
$('#saveStatus').text('Saved').fadeIn().delay(2000).fadeOut();
315
formChanged = false;
316
});
317
}
318
```
319
320
### Accessibility and UX
321
322
Improving form accessibility and user experience.
323
324
```javascript
325
// Focus management
326
$('#myForm').on('submit', function(e) {
327
const firstError = $('.error').first();
328
if (firstError.length) {
329
e.preventDefault();
330
firstError.focus();
331
}
332
});
333
334
// Real-time validation feedback
335
$('#email').on('blur', function() {
336
const email = $(this).val();
337
if (email && !isValidEmail(email)) {
338
$(this).addClass('invalid').attr('aria-invalid', 'true');
339
$('#emailError').text('Please enter a valid email').show();
340
} else {
341
$(this).removeClass('invalid').attr('aria-invalid', 'false');
342
$('#emailError').hide();
343
}
344
});
345
346
// Character count for textareas
347
$('#message').on('input', function() {
348
const maxLength = 500;
349
const currentLength = $(this).val().length;
350
const remaining = maxLength - currentLength;
351
352
$('#charCount').text(`${remaining} characters remaining`);
353
354
if (remaining < 0) {
355
$(this).addClass('over-limit');
356
} else {
357
$(this).removeClass('over-limit');
358
}
359
});
360
```