Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 779
Omar Avatar asked Oct 25 '11 10:10

Omar


1 Answers

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>
like image 177
hollandben Avatar answered Sep 28 '22 18:09

hollandben