获取从循环php创建的复选框的id

时间:2011-11-24 20:48:44

标签: php checkbox

我如何获得从使用php中的循环创建的这些复选框中选中的复选框的值:

<?php
while($rowequipment = mysql_fetch_assoc($sqlequipment)) {
   echo '<input type="checkbox" name="equipment[]" value="'.$rowequipment['equipmentid'].'"/>
         <input type="text" name="count[]" id="count[]" size="3" value=""/>' .
         $rowequipment['description']."<br />";
}
?>

2 个答案:

答案 0 :(得分:1)

上述评论者错误:HTML表单元素的名称属性属于CDATA 类型。因此,您的代码是正确的。 HTML definition found here

除非您需要在DOM树上使用JavaScript,否则id属性是无用的。如果您只想使用PHP处理控件的值,只需删除id s。

如果您发布数据,则会迭代名为equipment []的所有元素:

foreach( $_POST[ 'equipment' ] as checkBoxIndex => checkBoxValue ) {

   echo '<br />Checkbox ' . checkBoxIndex . ' has value [' . checkBoxValue . ']';

}

答案 1 :(得分:0)

Assuming you're generating these checkboxes in your PHP code and want to match those with checked = "checked" attribute later (maybe in other file).
As others mentioned, the HTML made by the code is not valid, fix it and then you can get what you want using DOM and XPath:

$html = new DOMDocument();
$html->loadHTML($yourMarkup);
$xpath = new DOMXpath($html);
$checkboxes = $xpath->query("*/input[@type='checkbox' and @checked='checked']");

if (!is_null($checkboxes)) { foreach ($checkboxes as $checkbox) { echo $checkbox->nodeValue; } }
<击> if (!is_null($checkboxes)) { foreach ($checkboxes as $checkbox) { echo $checkbox->nodeValue; } }

<击>

如果您想获取表单帖子上的复选框值,请使用哪个键是复选框$_POST['key']属性。