I have a for loop that forms a list of check boxes based on information received from a mySQL database. Below is the for loop that forms the check boxes (unnecessary code removed).
for ($i = 1; $i <= count($descriptionIDsArray); $i++) {
$statuses = mysql_fetch_assoc(mysql_query(sprintf("SELECT status, description FROM status_descriptions WHERE description_id='$i'")));
$status = $statuses["status"]; ?>
<input type="checkbox" value="<?php echo $status ?>" <?php if ($check == 1) {echo "checked='checked'";} ?> onchange="checkBox()" /><?php echo $description ?><br />
<?php } ?>
Checking or unchecking a box calls the following function:
<script type="text/javascript">
function checkBox() {
var status = $("input:checkbox").val();
document.getElementById("test").innerHTML = status;
}
</script>
The only value that I can get to appear in “test” is the value of the first check box. If I echo $status throughout the initial for loop all the values appear correctly so the problem seems to arise when the Javascript code is retrieving the corresponding value.
If you still want to keep the inline event handlers, change it to:
And change the function to:
Note that
onclickis better supported with checkboxes and radio buttons than isonchange. Also, the reason for this change I provided is because passingthisto thecheckBoxfunction references the element that theclickwas applied to. That way, you know that inside ofcheckBox, the parameterchkwill be the specific checkbox that just changed. Then just get the value with.valuebecause it’s a simple DOM node.Anyways, I’d suggest using jQuery to bind the
clickevent. Something like:But you can obviously use
$(this).val()instead ofthis.value, but why bother? If you use jQuery to bind the events, just make sure you take out theonchange/onclickinline event handler in the HTML.You can look at why to use
input:checkboxand not just:checkboxas the jQuery selector here: http://api.jquery.com/checkbox-selector/