jQuery: create a javascript ARRAY from an Element's CHILDREN

Omar picture Omar · Oct 25, 2011 · Viewed 14.5k times · Source

I am trying to create a JavaScript ARRAY, and get the name of an element's children.
(I do not need span elements, only input, select and textarea)

HTML:

<div id="new">
    ID: <input name="id" />
    <span>Date: </span>
    <input name="date" />
    <select name="status">
        <option>New</option>
        <option>Old</option>
    </select>
    <textarea name="memo"></textarea>
... etc.
</div> <!-- END: #new -->


jQuery:

var elements=new Array();
$("#new").each(function()
{
    elements = $(this).children('input, select, textarea').attr("name");
});


With this code I only get 1 element's name ("id"). When I test the array, with index 0, it works. BUT when I use a different index, say...to alert "date" or "status", it does not work:

alert( elements[0] ); //Output: "id"
alert( elements[2] ); //Output: "undefined". It should alert "status" instead

Answer

hollandben picture hollandben · Oct 25, 2011

a cleaner version that grabs all fields that require an input from the user:

jQuery

var elements = [];

//iterates through each input field and pushes the name to the array
$("#new :input").each(function() {
    var name = $(this).attr("name");
    elements.push(name);
});

And yes, you need to clean up your HTML. Should look like this:

HTML

<div id="new">
    ID: <input name="id" />
    <span>Date: </span>
    <input name="date" />
    <select name="status">
        <option>New</option>
         <option>Old</option>
    </select>    
    <textarea name="memo"></textarea>
</div>