Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery get each div's sub child divs and grab info into an array

I have a some html that looks like this

<div id="main">
  <div id="sub_main_1" class="sub_main">
      <input type="text" class="sub_name_first" /><br />
      <input type="text" class="sub_name_second" /><br />
  </div>
  <div id="sub_main_2" class="sub_main">
      <input type="text" class="sub_name_first" /><br />
      <input type="text" class="sub_name_second" /><br />
  </div>
</div>

I would like to pull out each sub_main divs information into an array in javascript. So far I have this as my jquery code

$('#main').find('.sub_main').each( 
          function() { 
               alert('hi'); 
          });

The alert is just a test that it should show "hi" twice. But this is not working. I am also not clear on how I can store the two inputs in a javascript array. Any help would be great! Thanks,

like image 811
McNabbToSkins Avatar asked Apr 27 '10 15:04

McNabbToSkins


People also ask

How to iterate through child elements of a div 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.

How do you access children in an array?

You can access the individual child nodes in the collection by using either the item() method on the collection, or by using JavaScript array-style notation. If the element has no element children, then children is an empty list with a length of 0 .

How do I get all Div children?

If You want to get list only children elements with id or class, avoiding elements without id/class, You can use document. getElementById('container'). querySelectorAll('[id],[class]'); ... querySelectorAll('[id],[class]') will "grab" only elements with id and/or class.


2 Answers

var array = $('#main input').map(function() {
    return $(this).val();
}).get();

EDIT:

Note that this will return the values of all input elements under #main. You can make the $('#main input') selector as specific as you need if not all input elements are desired.

like image 136
user113716 Avatar answered Sep 28 '22 10:09

user113716


var info = $("#main .sub_main input:text").map(function() {
    return $(this).val();
}).get(); // get() converts resulting collection into array

http://api.jquery.com/map/

like image 41
karim79 Avatar answered Sep 28 '22 10:09

karim79