Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two jQuery element objects? .add() isn't working

I'm inside a function and I need to return a jQuery object with two elements. Inside the function I have, for example:

function getInput() {
    $hiddenInput = $('<input type="hidden">');
    //(other code)
    $select = $('<select></select>');
    //(other code)
    $hiddenInput.add($select);
    return $hiddenInput;
}

And outside I have:

$myContainer.append(getInput());

The result expected would be:

<div id="container"><input type="hidden"><select></select></div>

But the only thing I get right now with .add() is only the input element and not the select. How can I joint those two form elements on the function return? If not possible with jQuery, then with plain JavaScript. Thanks a lot.

like image 900
Alejandro García Iglesias Avatar asked Aug 26 '10 17:08

Alejandro García Iglesias


People also ask

What is the use of jQuery each() function?

The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How to loop through html elements using jQuery?

jQuery Selector can be used to find (select) HTML elements from the DOM. Once an element is selected, the jQuery children() method is called to find all the child elements of the selected element. To loop through the child elements, the jQuery each() method is used as demonstrated in the following example.


3 Answers

add() creates (and returns) a new jQuery object that is the union of the original set and what you're adding to it, but you're still returning the original in your function. You seem to have wanted to do this instead:

function getInput() {
    $hiddenInput = $('<input type="hidden">');
    //(other code)
    $select = $('<select></select>');
    //(other code)
    return $hiddenInput.add($select);
}
like image 112
Tim Stone Avatar answered Oct 11 '22 14:10

Tim Stone


You can use

$hiddenInput.after($select);

That will put the $select after the $hiddenInput, achieving what you want to get.

like image 28
Jeff Rupert Avatar answered Oct 11 '22 14:10

Jeff Rupert


You can use the following:

this.MergejQueryObjects = function(arrayOfJqueryObjects) {
        return $($.map(arrayOfJqueryObjects, function (el) {
            return el.get();
        }));
    }
like image 44
Mohammad Dayyan Avatar answered Oct 11 '22 12:10

Mohammad Dayyan