Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .each() index value

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;

like image 605
Dimt Avatar asked Feb 18 '14 10:02

Dimt


1 Answers

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>');
    });
});
like image 68
Arun P Johny Avatar answered Oct 19 '22 16:10

Arun P Johny