strimp099 strimp099 - 1 month ago 6
jQuery Question

Return filtered results in array

I have the following HTML

button
s:

<button name="foo" class="one active">cat</button>
<button name="foo" class="one active">dog</button>
<button name="foo" class="one active">hamster</button>
<button name="foo" class="one">rhino</button>
<button name="foo" class="one">rat</button>


Given the following
jQuery
code:

var res = $('button[name=foo]', '#my-form').filter(function () {
return $(this).hasClass('active');
}).text();


res
ends up with the string
"catdoghamster"
when I would have expected the result in an array such as
["cat", "dog", "hamster"]
.

How do I filter the above buttons based on a class and return the
text
of the buttons in an array?

Answer

You probably wanted a map in addition to the filter, and then to return the text inside the map, not after it

var res = $('button[name=foo]', '#my-form').filter(function() {
  return $(this).hasClass('active');
}).map(function() {
  return $(this).text();
}).get();

console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="my-form">
  <button name="foo" class="one active">cat</button>
  <button name="foo" class="one active">dog</button>
  <button name="foo" class="one active">hamster</button>
  <button name="foo" class="one">rhino</button>
  <button name="foo" class="one">rat</button>
</form>

As a sidenote, the filter seems uneccessary, as you could just do

$('button[name=foo].active', '#my-form')