Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.