Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 411
Daniel Hunter Avatar asked Mar 15 '12 22:03

Daniel Hunter


3 Answers

    $('div','#main').each(function(){
      array.push($(this).attr('id')); 
    });
like image 174
Frenchi In LA Avatar answered Oct 15 '22 03:10

Frenchi In LA


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

like image 11
ipr101 Avatar answered Oct 15 '22 03:10

ipr101


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

$('#children').val(ids);
like image 3
A.r. Basith Avatar answered Oct 15 '22 05:10

A.r. Basith