Mastering jQuery: From DOM Manipulation to Dynamic Interactivity

5.44K 0 0 0 0

Chapter 5: jQuery Forms and Input Handling

🔹 1. Why Form Handling with jQuery Is Powerful

Forms are where your app connects to the user’s intent — whether it's signing up, logging in, or submitting data. jQuery gives you a clean and simple way to:

  • Access and validate inputs
  • Handle real-time user feedback
  • Prevent invalid submissions
  • Send AJAX form data without page reload

🔹 2. Getting and Setting Input Values

Accessing Values

let name = $("#username").val(); // Get

$("#username").val("John");      // Set

Selector

Method

Description

input/textarea

.val()

Get or set value

checkbox

.prop('checked')

Check if selected

select

.val()

Get selected value

Example:

<input type="text" id="email" />

<button id="getEmail">Check</button>

$("#getEmail").click(function(){

  alert("Email: " + $("#email").val());

});


🔹 3. Real-Time Input Validation

Keyup Event + Basic Check

$("#username").on("keyup", function() {

  let value = $(this).val();

  if(value.length < 3){

    $("#error").text("Username too short");

  } else {

    $("#error").text("");

  }

});

Show instant feedback as the user types = better UX.


🔹 4. Form Validation on Submit

$("form").on("submit", function(e){

  e.preventDefault(); // Prevent default reload

  let email = $("#email").val();

  if(email === ""){

    alert("Email is required.");

    return;

  }

  // Proceed with submission logic

});

Combine this with .test() and regex for deeper validation.


🔹 5. Working with Checkboxes & Radios

if($("#agree").prop("checked")) {

  console.log("User agreed to terms.");

}

Action

jQuery Code

Check status

.prop("checked")

Set value

.prop("checked", true)

Toggle

$('#cb').prop('checked', !this.checked)


🔹 6. Select Dropdown Handling

let plan = $("#planSelect").val(); // Get selected

$("#planSelect").val("pro");       // Set selected

Example:

<select id="planSelect">

  <option value="free">Free</option>

  <option value="pro">Pro</option>

</select>

$("#planSelect").change(function(){

  alert("Plan selected: " + $(this).val());

});


🔹 7. Preventing Default Behavior

Use this to stop forms from refreshing the page:

$("form").submit(function(e){

  e.preventDefault();

  // your logic here

});

Essential when handling forms via JavaScript or AJAX.


🔹 8. Submit Form with jQuery AJAX

<form id="loginForm">

  <input type="text" id="user">

  <input type="password" id="pass">

  <button type="submit">Login</button>

</form>

$("#loginForm").on("submit", function(e){

  e.preventDefault();

  let data = {

    user: $("#user").val(),

    pass: $("#pass").val()

  };

 

  $.post("/api/login", data, function(response){

    alert("Login Success!");

  }).fail(function(){

    alert("Login failed.");

  });

});


🔹 9. Showing/Hiding Submit Button Based on Validation

$("#email").on("keyup", function(){

  let isValid = $(this).val().includes("@");

  $("#submit").prop("disabled", !isValid);

});

Encourages users to correct mistakes before submitting.


🔹 10. Summary Table: jQuery Form Controls

Task

jQuery Code

Get input value

$("#field").val()

Set input value

$("#field").val("value")

Check if checkbox is checked

$("#cb").prop("checked")

Get dropdown selected

$("#select").val()

Prevent form from reloading

e.preventDefault() in .submit()

AJAX form submission

$.post("/url", data)



Back

FAQs


1. What is jQuery?

jQuery is a fast, small JavaScript library that simplifies HTML document traversal, manipulation, event handling, and AJAX.

2. Is jQuery still relevant today?

Yes while modern frameworks exist, jQuery remains heavily used in WordPress, older projects, CMSs, and quick prototypes.

3. What are the benefits of using jQuery?

It shortens code, handles cross-browser issues, simplifies AJAX, and is beginner-friendly.

4. How do I include jQuery in a webpage?

  1. Use a CDN:


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

5. What is the difference between $(document).ready() and window.onload?

$(document).ready() runs when the DOM is ready; window.onload waits for full page (including images) to load.

6. Can I use jQuery with other JavaScript libraries?

$(document).ready() runs when the DOM is ready; window.onload waits for full page (including images) to load

7. Is jQuery free to use in commercial projects?

Yes its open-source under the MIT license.

8. What's the difference between jQuery and JavaScript?

jQuery is a library built with JavaScript to simplify tasks like DOM handling and AJAX.

9. Does jQuery work on mobile browsers?

Yes it works across all major desktop and mobile browsers.

10. Should I learn jQuery before JavaScript?

It’s better to learn JavaScript fundamentals first, but jQuery is easier to grasp early on for quick UI work.