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

requiredValues method in jQuery

The instructions are: Create a method called 'requiredValues' that returns an array of all the values of inputs with the class of 'required'.

Here is my code:

function requiredValues() {
  var reqFields = new Array();
  $("input").each(function () {
    reqFields.push($(".required").val());
  });
  return reqFields;
}

The error message just says there's something wrong with my code. I've been going over it several times and I can't get it to work. Please help!

Thanks in advance.

2 Answers

Instead of iterating over all input fields, just iterate over elements with the class .required. Then, push the value of $(this) into the array.

var someArray = new Array();
$(".classYouNeed").each(function () {
  someArray.push($(this).val());
});

This worked great, thanks!

I see my mistake was not only that I was trying to loop over all the inputs, but that I was selecting the target elements wrong.

Thank you.

$('form.test').on('submit', function(){ var that = $(this), url = that.attr('action'), type = that.attr('method'), data = {};

    that.find('[name]').each(function(index, value){


        var that = $(this),
            name = that.attr('name'),
            value = that.val();

        data[name] = value; 

    });

        $.ajax({
            url:url,
            type:type,
            data:data,
            success:function(output){
            $('#res').html(output).slideDown("slow");

            }

        });

    return false;

//This is the jquery version that will work.. Create a form with the name test or you can change it..... You can modify the code once you keep the structure it will work like a charm.. Note the page will not fefresh when you submit.. just change false at the end to true.