</>
Skip to content
jQuery lessons (36/39)

jQuery — Forms

Form Submit

$("form").submit(function(e) {
    e.preventDefault();
    var data = $(this).serialize();
    $.post("/submit", data, function(response) {
        console.log("Submitted:", response);
    });
});

serialize()

var formData = $("form").serialize();
// "name=John&email=john@example.com"

serializeArray()

var formData = $("form").serializeArray();
// [{name: "name", value: "John"}, ...]

Getting Input Values

var name = $("#name").val();
var checked = $("input:checkbox:checked").map(function() {
    return $(this).val();
}).get();

Setting Input Values

$("#name").val("John");
$("input:radio[value='yes']").prop("checked", true);
$("select").val("option2");

Form Events

$("input").focus(function() { $(this).addClass("active"); });
$("input").blur(function() { $(this).removeClass("active"); });
$("input").change(function() { console.log("Changed"); });

File Input

$("#file").change(function() {
    var file = this.files[0];
    console.log(file.name, file.size);
});

Practical Form Handling

$("#myForm").on("submit", function(e) {
    e.preventDefault();
    var $btn = $(this).find("button");
    $btn.prop("disabled", true).text("Saving...");
    
    $.post("/api/save", $(this).serialize())
        .done(function() { $btn.text("Saved!"); })
        .fail(function() { $btn.text("Error").prop("disabled", false); });
});

Mini Practice

  1. Handle form submission with preventDefault
  2. Serialize form data
  3. Get and set input values
  4. Create a loading state during submission

Up Next

Continue with Selectors Reference — a complete list of jQuery selectors.

Related Topics

Frequently Asked Questions about Forms

What is Forms in jQuery?

Forms is a fundamental concept in jQuery. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Forms?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Forms.

Why is Forms important in jQuery?

Forms is essential for jQuery development. Understanding this concept will help you write better code and solve real-world problems more effectively.