Explain Codes LogoExplain Codes Logo

How to retrieve checkboxes values in jQuery

javascript
event-delegation
checkbox-handling
jquery
Alex KataevbyAlex Kataev·Dec 24, 2024
TLDR

Retrieve checked checkbox values with jQuery using .map() and :checked. Behold, the magic of jQuery!

var checkedValues = $('input:checkbox:checked').map((_, el) => el.value).get();

This code assembles an array, checkedValues, with the values of all checked checkboxes. Now, you can use these values in whatever fiendish plan you have next!

Step-by-step breakdown

Tracking changes in real-time

With DOM changes during dynamic content updates like Ajax actions, you need to trace these using .on() attached to a static parent; the Document is a universal parent. Why play favourites, right?

$(document).on('change', 'input:checkbox', function() { updateValues(); // Gather the troops! }); function updateValues() { var checkedValues = $('input:checkbox:checked').map((_, el) => el.value).get(); // checkedValues is a secret club of checked boxes }

Whoosh! The checkbox updates keep up with user interactions in a flash!

The reusable magic trick

For reusability, define a custom function that can be called wherever checkbox handling is needed. It's like having a magic trick up your sleeve!

function getCheckedCheckboxes(selector) { return $(selector).map(function() { return this.checked ? this.value : null; // Only the worthy shall pass! }).get(); } // Usage var checkedValues = getCheckedCheckboxes('input.your-class:checkbox');

Maximizing modularity and reusability... It's cleaner, it's leaner!

The efficient event handler

Use delegate event handling to capably manage the checkbox events, like a puppet master pulling strings!

$('#form-id').on('click', 'input:checkbox', function() { // Behold, the checkbox clicked! });

Event delegation handles checkboxes that are dynamically added to the form. Delegate like a boss!

Manifesting to a textarea

Ever considered showing the values in a textarea? Let's update it in real-time, just like magic:

$('input:checkbox').on('change', function() { var checkedValues = $('input:checkbox:checked').map((_, el) => el.value).get().join(', '); $('#output-textarea').val(checkedValues); // Voila! Real-time magic });

Watch in amazement as the textarea gets instantly updated as the checkboxes are changed. Now that's user interaction par excellence!

SQL queries considerations

While using checkbox values for SQL queries, remember, SQL injections are more harmful than Botox! Always sanitize your values before sending them to server-side where they should be parameterized for safety.