使用jquery检查php数组中的复选框需要帮助
我有一个php数组,我试图让jQuery检查这些复选框,但我似乎无法让它工作。我的php数组名为“toCheck”,即:使用jquery检查php数组中的复选框需要帮助,php,jquery,arrays,checkbox,Php,Jquery,Arrays,Checkbox,我有一个php数组,我试图让jQuery检查这些复选框,但我似乎无法让它工作。我的php数组名为“toCheck”,即: Array ( [0] => 0 [1] => 3 [2] => 4 ) 0,3,4是我需要选中的复选框。这是我的复选框: <input type="checkbox" name="correct[0]" id="correct" value="0" /> <input type="checkbox" name="
Array
(
[0] => 0
[1] => 3
[2] => 4
)
0,3,4是我需要选中的复选框。这是我的复选框:
<input type="checkbox" name="correct[0]" id="correct" value="0" />
<input type="checkbox" name="correct[1]" id="correct" value="1" />
<input type="checkbox" name="correct[2]" id="correct" value="2" />
<input type="checkbox" name="correct[3]" id="correct" value="3" />
<input type="checkbox" name="correct[4]" id="correct" value="4" />
<input type="checkbox" name="correct[5]" id="correct" value="5" />
如果有人能指出用什么jQuery来选中这些复选框,那就太好了
<?php foreach($toCheck as $checkMe) { ?>
//i'm assuming my jquery goes here but I can't get it working
<?php }; ?>
//我假设我的jquery在这里,但我无法让它工作
提前感谢:)您的HTML无效<代码>id值在文档中必须是唯一的() 也就是说,忽略
id
值,可以使用以下()命令:
它使用name
属性上的CSS3子字符串选择器(jQuery支持几乎所有的CSS3)选择名称以correct
开头的任何复选框,然后使用jQuery循环遍历它们。然后,我们将checked
属性设置为具有所需值的属性
您还可以使用更长的选择器,而不使用循环():
更新:重新阅读您的问题,您可能需要更动态地执行此操作:
<script type='text/javascript'>
(function() {
var boxes = $(); // Assumes jQuery 1.4 or higher
<?php foreach($toCheck as $checkMe) { ?>
echo "boxes.add(':checkbox[name=^=correct][value=" . $toCheck . "]');";
<?php }; ?>
boxes.attr('checked', true);
})();
</script>
(功能(){
var-box=$();//假设jQuery 1.4或更高版本
echo“box.add(':checkbox[name=^=correct][value=“.$toCheck.”]);”;
box.attr('checked',true);
})();
…这将产生:
<script type='text/javascript'>
(function() {
var boxes = $(); // Assumes jQuery 1.4 or higher
boxes.add(':checkbox[name=^=correct][value=0]');
boxes.add(':checkbox[name=^=correct][value=3]');
boxes.add(':checkbox[name=^=correct][value=4]');
boxes.attr('checked', true);
})();
</script>
(功能(){
var-box=$();//假设jQuery 1.4或更高版本
添加(':复选框[name=^=correct][value=0]);
添加(':复选框[name=^=correct][value=3]);
添加(':复选框[name=^=correct][value=4]);
box.attr('checked',true);
})();
…这将选中相关框。但这不是很有效(所有文档遍历),最好使用PHP将值组合到选择器或开关中,如上图所示。请注意,浏览器不会提交未选中的复选框
有关更多信息,请参阅。非常感谢,我将修复我的ID并使用上面的:)
<script type='text/javascript'>
(function() {
var boxes = $(); // Assumes jQuery 1.4 or higher
<?php foreach($toCheck as $checkMe) { ?>
echo "boxes.add(':checkbox[name=^=correct][value=" . $toCheck . "]');";
<?php }; ?>
boxes.attr('checked', true);
})();
</script>
<script type='text/javascript'>
(function() {
var boxes = $(); // Assumes jQuery 1.4 or higher
boxes.add(':checkbox[name=^=correct][value=0]');
boxes.add(':checkbox[name=^=correct][value=3]');
boxes.add(':checkbox[name=^=correct][value=4]');
boxes.attr('checked', true);
})();
</script>