Omar Juvera
Omar Juvera

Reputation: 12297

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

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

Upvotes: 7

Views: 16118

Answers (3)

hollandben
hollandben

Reputation: 322

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>

Upvotes: 12

ipr101
ipr101

Reputation: 24236

You could use map (docs) -

var arr = $("#new").children('input, select, textarea').map(function() {
    return $(this).attr("name");
});

map will iterate over each element in the selected element set and the return the specified value into the arr array.

You also need to tidy your HTML up a bit as you're missing some closing tags which is causing the children collection to populate incorrectly -

<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>

Demo - http://jsfiddle.net/M52G4/1

Upvotes: 5

totallyNotLizards
totallyNotLizards

Reputation: 8569

quick and dirty, wouldn't recommend for real life, but theoretically:

var arr = new Array();   //initialise array
$('#new').children().each(function(){  

    //iterate through the children of the div - 
    //there shouldn't be more than one #new, unless you aren't 
    //following best practices :)

    if ($(this).attr('name'))
    {
        //if the name attr is defined, push it to the array
        arr.push($(this).attr('name'));
    }
});        
alert(arr);

fiddle: http://jsfiddle.net/GMNKm/

Upvotes: 0

Related Questions