Jquery gets each div div a child div and grabs information into an array

I have some html that looks like

<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 each sub_main divs information into an array in javascript. So far I have it like my jquery code

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

A warning is just a test that should show hi twice. But that does not work. I also don't understand how I can store two inputs in a javascript array. Any help would be great! Thank,

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

EDIT:

Note that this will return the values ​​of all elements inputin the section #main. You can make the selector $('#main input')as specific as possible, if not all elements input.

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

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

+3

DOM?

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

div "" div,

$('.main>div')

This will result in the selection of all children of any class of the class "main".

0
source

why not just do something simple:

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());
   }
});

Of course, this is not the best way, but I just wrote that after 1 minute it works

0
source

All Articles