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...

3
  • 1
    u can use jquery like : stackoverflow.com/questions/786142/… Commented Jan 25, 2010 at 10:10
  • @haim he was asking for javascript i think so.. Commented Jan 25, 2010 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... Commented Jan 25, 2010 at 11:04

3 Answers 3

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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;
}
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.