10

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
  • 2,546
  • 6
  • 28
  • 34
  • We know it's not right. What *exactly* do you know is wrong with it? Are there any *specific* errors? – Jon Egeland Mar 15 '12 at 22:50
  • Check your quotes and brackets! Spoiler: minus quote after main plus right parenthesis after id quote plus right parenthesis after first } – The Nail Mar 15 '12 at 22:53
  • Syntax highlighting is exactly for what you can see. It tells you there's something wrong. – elclanrs Mar 15 '12 at 22:53
  • sorry, copy and paste, then change certain variables for simplicity. fixed... alert(input_value); is empty – Daniel Hunter Mar 15 '12 at 22:56

4 Answers4

16
    $('div','#main').each(function(){
      array.push($(this).attr('id')); 
    });
Frenchi In LA
  • 3,139
  • 3
  • 25
  • 41
11

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

ipr101
  • 24,096
  • 8
  • 59
  • 61
3
var ids = $('#main > td').map(function(){
                 return this.id
           }).toArray(); 

$('#children').val(ids);
  • @ThiefMaster: All my new posts are now CW. I'm just liking it better that way for some reason. –  Mar 15 '12 at 23:13
1

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

Steve
  • 8,609
  • 6
  • 40
  • 54