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,
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.
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 .
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.
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.
var info = $("#main .sub_main input:text").map(function() {
return $(this).val();
}).get(); // get() converts resulting collection into array
http://api.jquery.com/map/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With