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
$('div','#main').each(function(){
array.push($(this).attr('id'));
});
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
var ids = $('#main > td').map(function(){
return this.id
}).toArray();
$('#children').val(ids);
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