get each child('id') into array or string
27,021
Solution 1
$('div','#main').each(function(){
array.push($(this).attr('id'));
});
Solution 2
You could use map
-
var arr = $("#main > div").map(function() {return this.id});
$('#children').val(arr.get().join(","));
The code above relies on your HTML being changed to -
<div id="main">
<div id="A"></div>
<div id="B"></div>
<div id="C"></div>
</div>
The map
function will return a jQuery object containing the ids of each div contained within the 'main' div. You can the call the get()
function to turn the object returned by the map
function into a Javascript array, and then use the join
function to return a comma delimited string.
Demo - http://jsfiddle.net/8tZXH/1
Solution 3
You probably want to use children('div')
, not children('id')
Comments
-
Daniel Hunter over 4 years
I need to create a comma separated value for a hidden input created from a series of div id's
<div id="main"> <div id="A"></div> <div id="B"></div> <div id="C"></div> </div> <input type="hidden" id="children"/>
I want to use jquery but having trouble with the function
function update_input(main){ var array = new Array(); $('#'+main).children('id').each(function(){ array.push($(this).attr('div')); }); input_value = array.toString(); $('#children').val(input_value); }
This is not right
-
Daniel Hunter over 12 yearsI am using this one. Thank you for the help.