Daniel Hunter
Daniel Hunter

Reputation: 2896

get each child('id') into array or string

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

Upvotes: 10

Views: 27780

Answers (4)

ipr101
ipr101

Reputation: 24236

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

Upvotes: 11

Steve
Steve

Reputation: 8640

You probably want to use children('div'), not children('id')

Upvotes: 1

Frenchi In LA
Frenchi In LA

Reputation: 3169

    $('div','#main').each(function(){
      array.push($(this).attr('id')); 
    });

Upvotes: 16

user1106925
user1106925

Reputation:

var ids = $('#main > td').map(function(){
                 return this.id
           }).toArray(); 

$('#children').val(ids);

Upvotes: 3

Related Questions