I have a php array which I'm trying to get jQuery to check those checkboxes, but I can'开发者_如何转开发t seem to get it working. My php array name is "toCheck" which is:
Array
(
[0] => 0
[1] => 3
[2] => 4
)
0,3,4 are the checkboxes I need checked. Here's my checkboxes:
<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" />
If someone could point out what jQuery to use to make these checkboxes selected, that would be great!
<?php foreach($toCheck as $checkMe) { ?>
//i'm assuming my jquery goes here but I can't get it working
<?php }; ?>
Thank you in advance :)
Your HTML is invalid. id
values must be unique within a document (reference).
That said, ignoring the id
values, you could use this (live example):
$(':checkbox[name^=correct]').each(function() {
switch (this.value) {
case "0":
case "3":
case "4":
this.checked = true;
break;
}
});
That uses a CSS3 substring selector (jQuery supports nearly all of CSS3) on the name
attribute to select any checkbox with a name starting with correct
, and then uses jQuery's each
to loop through them. Then we set the checked
property on the ones with the desired value
.
You could also do it with a longer selector and without the loop (live example):
$(':checkbox[name^=correct][value=0], :checkbox[name^=correct][value=3], :checkbox[name^=correct][value=4]').attr('checked', true);
Update: Re-reading your question, it looks like you might need to do this more dynamically:
<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>
...which would generate:
<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>
...which would check the relevant boxes. But it wouldn't be very efficient (all of that document traversal), better off using PHP to combine the values into a selector or switch
as shown above.
Be aware that browsers don't submit unchecked checkboxes.
See Submit an HTML form with empty checkboxes for more.
精彩评论