0

I have a jQuery function to return the values of checked checkboxes in a form:

$.fn.selected_values = function() {
    return $(this).map( function() { if( $(this).is(':checked') ) { return this.value; } } ).get().join(",");
};

I was wondering if there is a less cumbersome way to say "$this, plus another criteria". In other words, rather than using if( $(this).is('checked'){...} in a loop, is there some way to say something like $(this):checked ? Then I could do something like:

$.fn.selected_values = function() {
    return $(this):checked.map( function() { return this.value; } ).get().join(",");
};

The existing code does work, but it seems that over time such a selector could result much more readable code. Does it exist?

Stephen R
  • 3,512
  • 1
  • 28
  • 45

2 Answers2

2

You're looking for the filter method, which filters a jQuery object to only include elements that match a selector.

Side note: Inside a jQuery method, this is already a jQuery object (just like any other class instance method); there is no reason to write $(this).

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • this.filter(':checked') is exactly what I was looking for. Thanks! – Stephen R Jun 29 '17 at 16:35
  • For people reading this later, more info on `$(this)` vs. `this`: https://stackoverflow.com/questions/1051782/jquery-whats-the-difference-between-this-and-this – Stephen R Jun 29 '17 at 17:06
0

Use :checked selector this way:

$('input.email_toggle:checked')
sinedsem
  • 5,413
  • 7
  • 29
  • 46
  • I'm trying to keep things as clean as possible for the end user. As "checked" is a part of the selector **by definition** when fetching values of selected items, I want it contained in the function itself. – Stephen R Jun 29 '17 at 16:31