A jQuery if statement uses standard JavaScript syntax: if (condition) { ... } else { ... } with jQuery selector methods inside the condition. Because jQuery is a JavaScript library built on JavaScript, there is no special syntax. You check states like $(element).is(':checked') or $(element).val() === 'value' to control DOM behaviour conditionally and efficiently.
- jQuery is a JavaScript library, not a separate language. Every jQuery method runs on top of vanilla JS.
- Selectors like
$('#id')replacedocument.getElementById()and return a jQuery object you can chain methods on. - Event handlers such as
.on('change', fn)and.on('click', fn)cover checkbox events, dropdown changes and button clicks in a few readable lines. - AJAX calls through
$.ajax()give yousuccess,errorandcompletecallbacks so you can show progress feedback and handle a 500 internal server error gracefully. - Smooth scroll to a div needs just
$('html, body').animate({ scrollTop: ... })and a target element’s.offset().topvalue.
How to Write a jQuery if Statement
A jQuery if statement is identical in structure to a plain JavaScript if statement. The condition inside the parentheses can be any expression that evaluates to true or false, including jQuery methods that inspect DOM state. The most common patterns are:
if ($(this).is(':checked'))— tests whether a checkbox is tickedif ($(this).val() === 'option1')— tests the selected value of a dropdownif ($('#el').hasClass('active'))— tests whether an element carries a CSS classif ($('#el').is(':visible'))— tests element visibility
Every if condition in jQuery follows the same rule: whatever sits inside if ( ) must resolve to a truthy or falsy value. jQuery selector methods like .is(), .val() and .hasClass() all return values that work directly inside a standard JavaScript if statement.
jQuery and JavaScript: What Actually Differs
JavaScript is the programming language that browsers run natively. jQuery, first released by John Resig in 2006, is a lightweight library written in JavaScript that simplifies common tasks like DOM manipulation, event binding and AJAX requests. According to W3Techs data published in early 2025, jQuery is still used on roughly 77% of all websites that use a JavaScript library, making it the most deployed JS library on the web.
The practical difference comes down to verbosity. Selecting all paragraphs with a class in vanilla JS takes three or four lines with document.querySelectorAll() and a loop. In jQuery it is $('p.intro').hide() on a single line. That compression is why Indian computer science curricula, from NIIT to full-stack bootcamps, still teach jQuery before moving to frameworks like React.
When to Use jQuery vs Vanilla JavaScript
| Scenario | Better Choice | Reason |
|---|---|---|
| Adding event listeners across browsers (2015 and earlier) | jQuery | Handled IE quirks automatically; jQuery minified size: 87 KB |
| Modern single-page applications | Vanilla JS or React/Vue | Frameworks manage state; jQuery adds unnecessary payload |
| Quick DOM manipulation in a WordPress theme or plugin | jQuery | Already bundled in WordPress core; zero extra dependency cost |
| AJAX calls in a Node.js backend | Fetch API or Axios | jQuery requires a browser DOM; Axios is ~14 KB gzipped |
| Legacy enterprise projects in Indian IT services firms | jQuery | Existing codebase; maintenance contracts; lower retraining cost |
If you are weighing which skills to learn first, check out our guide on top skills every college student must learn before graduation — jQuery sits comfortably alongside HTML, CSS and basic backend knowledge.
jQuery if Statement with Checkboxes, Dropdowns and Button Control
Conditional logic in jQuery follows standard JavaScript syntax. The jQuery if statement checks whatever expression evaluates to true or false, including jQuery selector states. Here is a practical pattern that covers checkbox events and a dropdown change together:
Checkbox checked event:
$('#myCheckbox').on('change', function () {
if ($(this).is(':checked')) {
$('#submitBtn').prop('disabled', false);
} else {
$('#submitBtn').prop('disabled', true);
}
});
The .prop() method is the correct way to read or set boolean attributes like disabled and checked. Using .attr('disabled', true) still works in older code, but .prop() has been the recommended approach since jQuery 1.6.
Getting a Select Dropdown Value in jQuery
Reading the selected option from a <select> element uses .val(). Combine it with a select onchange jQuery handler to react instantly when the user picks a new option. This is a real-world jQuery if else pattern:
$('#courseSelect').on('change', function () {
var selected = $(this).val();
if (selected === 'cybersecurity') {
$('#courseInfo').text('Enrol in our Ethical Hacking track.');
} else if (selected === 'ai') {
$('#courseInfo').text('Explore our AI and ML certification.');
} else {
$('#courseInfo').text('Choose a course to see details.');
}
});
The $(this).val() call is equivalent to reading selectElement.value in vanilla JS, just shorter and chainable. Each branch of the jQuery if statement updates a different piece of the UI without a page reload.
Enable and Disable a Button with jQuery
Button enable disable in jQuery is a single line either way. To disable: $('#btn').prop('disabled', true);. To enable: $('#btn').prop('disabled', false);. A common pattern is disabling a submit button until a form is valid, then re-enabling it on the fly:
$('#emailInput').on('keyup', function () {
var val = $(this).val().trim();
$('#submitBtn').prop('disabled', val.length < 5);
});
This keeps the UX clean without a full validation library. It is the kind of snippet you would write in an internship on your first week, and it is also the kind of thing that comes up in junior developer interviews at Indian product companies like Zoho and Freshworks.
jQuery Scroll to Div and AJAX with Progress and Error Handling
Smooth Scroll to a Div
The classic jQuery scroll to div technique animates scrollTop on the html, body selector. You grab the target element's position with .offset().top and pass it to .animate():
$('#scrollBtn').on('click', function () {
$('html, body').animate({
scrollTop: $('#targetSection').offset().top - 80
}, 600);
});
The - 80 offset accounts for a fixed navigation bar, which most Indian e-learning sites and dashboards have. The second argument, 600, is the duration in milliseconds. Shorter values feel snappier; anything above 1000 ms starts to feel sluggish on mobile.
AJAX with Progress Feedback and Error Handling
A solid $.ajax() call should always include a beforeSend callback for showing an AJAX progress indicator, a success handler for the happy path, and an error handler for failures including the dreaded 500 internal server error on AJAX POST requests. A jQuery if statement inside the error callback lets you branch on specific HTTP status codes:
$.ajax({
url: '/api/submit',
method: 'POST',
data: { name: 'Riya', course: 'ethical-hacking' },
beforeSend: function () {
$('#progressBar').show();
},
success: function (response) {
$('#progressBar').hide();
$('#message').text('Submitted successfully!');
},
error: function (xhr, status, error) {
$('#progressBar').hide();
if (xhr.status === 500) {
$('#message').text('Server error. Please try again later.');
} else if (xhr.status === 0) {
$('#message').text('No internet connection detected.');
} else {
$('#message').text('Error ' + xhr.status + ': ' + error);
}
},
complete: function () {
$('#submitBtn').prop('disabled', false);
}
});
The error callback receives the XMLHttpRequest object as its first argument. Reading xhr.status inside a jQuery if statement lets you branch on specific HTTP codes rather than showing a generic failure message. A 500 means something broke server-side; a 401 means the session expired; a 0 usually means the request never left the browser because of a network drop.
If you want a visual AJAX progress bar instead of a spinner, libraries like NProgress (by Rico Sta. Cruz, around 2 KB gzipped) integrate cleanly. Call NProgress.start() in beforeSend and NProgress.done() in complete.
Learning these patterns properly is one of the fastest ways to move from beginner to job-ready. Our list of top online courses for high salary jobs in 2025 covers full-stack paths that build directly on this jQuery foundation. And if you are looking for zero-cost resources to practise, the best free online learning platforms for students in 2025 lists places where jQuery tutorials are available without spending a rupee.
According to Stack Overflow's 2024 Developer Survey, JavaScript remains the most commonly used programming language for the 12th consecutive year, with 62.3% of respondents using it. jQuery's share in that ecosystem is shrinking in greenfield projects, but it stays dominant in maintenance roles. For students targeting entry-level developer jobs, knowing how to write a jQuery if statement and handle AJAX still gives you an edge in legacy-heavy IT services companies that make up a large slice of India's 5.4 million-strong IT workforce (NASSCOM, 2024).
Once you are comfortable with these basics, the next logical step is picking a career direction. Our guides on choosing the right career path after graduation and the best career options in 2026 for students and professionals break down which technical specialisations are seeing the most demand and the highest salary growth in India right now.
Frequently Asked Questions
What is a jQuery if statement?
A jQuery if statement uses standard JavaScript syntax: if (condition) { ... } else { ... }. The condition typically contains a jQuery method such as $(this).is(':checked') for a checkbox or $(this).val() === 'value' for a dropdown. There is no special jQuery-only syntax for conditionals. It is plain JavaScript with jQuery selector methods inside the condition brackets.
What is the difference between jQuery and JavaScript?
JavaScript is the programming language that browsers execute natively. jQuery is a library written in JavaScript that simplifies DOM manipulation, event handling and AJAX calls. Every jQuery method is JavaScript under the hood. You can do anything jQuery does in vanilla JS, but jQuery reduces the amount of code you write, especially for cross-browser compatibility in older projects.
How do you write an if else statement in jQuery?
A jQuery if else statement follows standard JavaScript: if (condition) { ... } else if (otherCondition) { ... } else { ... }. Use jQuery methods inside the condition, for example if ($(this).val() === 'cybersecurity') { ... } else if ($(this).val() === 'ai') { ... }. Chain as many else if branches as needed. The logic is identical to vanilla JavaScript.
How do you enable or disable a button with jQuery?
Use the .prop() method: $('#btn').prop('disabled', true) disables the button and $('#btn').prop('disabled', false) enables it. Avoid .attr() for boolean attributes like disabled. You can pass a variable or expression directly: $('#btn').prop('disabled', inputValue.length === 0) to toggle dynamically based on form state.
How do you handle an AJAX error in jQuery?
Add an error callback to your $.ajax() call. The callback receives the XMLHttpRequest object, a status string and an error message. Use a jQuery if statement to check xhr.status and handle specific codes: 500 for internal server errors, 401 for session expiry, 0 for no network connection. Always hide any progress indicator in the complete callback so it clears on both success and failure.
How do you scroll to a div using jQuery?
Use $('html, body').animate({ scrollTop: $('#targetDiv').offset().top }, 600);. The .offset().top gives the element's distance from the document top in pixels. Subtract a fixed number (like 80) if your site has a sticky header. The second argument is animation duration in milliseconds. Lower values scroll faster; 400 to 700 ms works well for most sites.
Mastering the jQuery if statement and these related patterns gives you a real, transferable skill set that applies directly to freelance projects, internships and full-time developer roles. If you want to go further and build expertise in high-demand areas like Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain or Web3, explore the certification courses at 3.0 University. The programmes are designed for students, working professionals and career switchers who want practical, industry-ready skills without spending years in a classroom.
Last updated: September 2026. Reviewed by the 3University editorial team.