0

How to find checkbox values from Dynamically generated Divs in php using javascript?

Here is my code,

echo "<input type='text' name='chkID' id='chkID'>
   <div id='mainDiv'>";

 while($rowset = mysql_fetch_array($result))
  {
    echo "<div style='float:left; width=10px; border:solid 1px;'>
    <input type='checkbox' value =".$rowset[0].">".$rowset[0]."</div>
   <div style='float:left; width=200px; border:solid 1px;'>".$rowset[1].''.$rowset[2]."
   </div></br></br>";
  }

 echo '</div>';

I want to display the values of checkboxes selected which would be like (1,2,3) in the chkID textbox... I want it to be done using javascript...

M Y T H
  • 97
  • 2
  • 7
  • 1
    u can use jquery like : http://stackoverflow.com/questions/786142/how-to-retrieve-checkboxes-values-in-jquery – Haim Evgi Jan 25 '10 at 10:10
  • @haim he was asking for javascript i think so.. – ACP Jan 25 '10 at 10:18
  • @Felix i agree with u... If he wanted it to be done in jquery he would have tagged jquery for the above question... – ACP Jan 25 '10 at 11:04

3 Answers3

3

If I understand your question correctly, this might be what you're looking for.

var mainDiv = document.getElementById('mainDiv');
var inputs = mainDiv.getElementsByTagName('input');
var values = [];

for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].type == 'checkbox') {
        values.push(inputs[i].value);
    }
}
nikc.org
  • 16,462
  • 6
  • 50
  • 83
0

First of all you need to add an unique name name and id to the input tags:

echo "...
<input type='checkbox' name='checkbox".$num."' id='checkbox".$num."' value ='".$rowset[0]."' />
...";
$num++;

(Also you need too look at your syntax: missing quotes (') and at the end of the tag a slash (/))

Then you can find the checkboxes with this simple JavaScript:

alert(document.findElementById("checkbox1").value);

Change the number to find the other checkboxes. Use a loop or something if you want to find all checkboxes.

Veger
  • 37,240
  • 11
  • 105
  • 116
0

this should do the work:

var div= document.getElementById('mainDiv');
var txt=document.getElementById('chkID');
var children=div.children;
for(var i=0;i<children.length;i++)
{
if(children[i].nodeName.toLowerCase()=='div')
{
if(children[i].children !=null && children[i].children.length>0 && children[i].children[0].nodeName.toLowerCase()=='input' )
{
txt.value=txt.value + ' ' + children[i].children[0].value;
}
}
}

TeKapa
  • 546
  • 2
  • 5