7

I’ve been teaching my self JavaScript and jQuery for a few months, but I’m still getting confused with JavaScript objects and jQuery objects.

In the following example I assigned a jQuery object to the variable $target. The $target should consist of an array of two objects.

My question is why I have to wrap the value variable again into the jQuery object in .each() function ?

$('select.to_append').change(function(){
    var $target = $('select.to_append');
    var $form = $('#anotherForm');

    $.each($target, function(key, value){
        $form.append('<input name="' + $(value).attr('name') + '" type="hidden" value="' + $(value).val() + '"></input>');
    });
});

The sample code I use to append values from selects which are not parts of the form being submitted;

1 Answer 1

8

because $target is a jQuery object, but when you iterate you will get a dom element reference in your iteration handler not a jQuery object. So if you want to access jQuery methods on that object you need to wrap the object again.

By the way to iterate over a jQuery object you can use .each() instead of jQuery.each()

$('select.to_append').change(function () {
    var $target = $('select.to_append');
    var $form = $('#anotherForm');

    $target.each(function (index, el) {
        $form.append('<input name="' + $(el).attr('name') + '" type="hidden" value="' + $(el).val() + '"></input>');
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I'm going to look up for difference between those two functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.