views:

136

answers:

5

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,

A: 

Are you waiting for the DOM to load?

$(document).ready(function(){
     $('#main').find('.sub_main').each( 
          function() { 
               alert('hi'); 
     });
 });
Luis
I am actually running this in a javascript function, the DOM has alreayd been loaded and the javascript function is called from the page after it has been loaded to the DOM.
McNabbToSkins
A: 

if you want to pull out the child divs of your 'main' div, use

$('.main>div')

This will select all div children of anything with the class of 'main'.

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

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

karim79
+5  A: 
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.

patrick dw
A: 

why not just do something simple like this:

var firsts = [];
var seconds = [];
("#main .sub_main input").each(function(){
   var $this = $(this);
   if($this.is(".sub_name_first"){
     firsts.push($this.val());
   } else {
     seconds.push($this.val());
   }
});

sure, its not the best way, but i just wrote that in 1 minute and it works

mkoryak