简体   繁体   English

使用JavaScript从php中动态生成的Divs中查找复选框值

[英]Find checkbox values from Dynamically generated Divs in php using javascript

How to find checkbox values from Dynamically generated Divs in php using javascript? 如何使用JavaScript在php中从动态生成的Divs中查找复选框值?

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... 我想在chkID文本框中显示与(1,2,3)相似的复选框的值...我希望使用javascript完成...

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

First of all you need to add an unique name name and id to the input tags: 首先,您需要在输入标签中添加唯一的名称nameid

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: 然后,您可以使用以下简单的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. 如果要查找所有复选框,请使用循环或其他方式。

这应该做的工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM