Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build an Interactive Website Form Validation and Manipulation Checking Values

Returning an array from a class in jQuery

Here is the question and I have no idea how to return the answer in jQuery

Create a method called 'requiredValues' that returns an array of all the values of inputs with the class of 'required’.

Here is what I have so far, I tried a few solutions and never got the answer I need. function requiredValues() { var $required = $(".required"); return new Array($required); }

2 Answers

Hi Matt,

It looks like you're trying to return an array of a jQuery object rather than an array which contains all the values that the user has entered into the 'required' fields.

They want you to iterate over all the required fields and save each of the values into an array and then return that array.

jQuery has a .each() method which will iterate over a jQuery object and then execute a function for each element. Inside the function, you want to get the value of the input and push it onto an array. After that is completed, you can return the array.

Here's the code I used:

function requiredValues () {
  var values = [];

  $('.required').each (function() {
    values.push($(this).val());
  });

  return values;
}

The jQuery selector code returns an array by itself. No need to do anything with it. You can go ahead and return the $required var, or even skip that step completely and just return $(".required");

EDIT: Pardon, jQuery returns an object with all of the elements. Jason above is correct.