Jump to content

Check All/Clear All Checkboxes


Dysan

Recommended Posts

The following PHP code create a simple 2x2 table along with a check box for each row.

 

Using JavaScript, how do I create a script, that 'Checks All' check boxes upon the top (title) check box being clicked, then if the top (title) check box is clicked again, 'Clears All' check boxes?

 

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
  die(mysql_error());
}

mysql_select_db("db", $con);

$result = mysql_query("SELECT * FROM person");

echo '<table border="1">
<tr>
<th><input type="checkbox" name="checkbox" value="checkbox"></th>
<th>First Name</th>
<th>Last Name</th>
</tr>';

while($row = mysql_fetch_array($result))
{
  echo '<tr>';
  echo '<td><input type="checkbox" name="checkbox" value="checkbox"></td>';
  echo '<td>'.$row['FirstName'].'</td>';
  echo '<td>'.$row['LastName'].'</td>';
  echo '</tr>';
}
echo '</table>';

mysql_close($con);
?>

Link to comment
https://forums.phpfreaks.com/topic/83481-check-allclear-all-checkboxes/
Share on other sites

try this:

 

<form name="form1">

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
  die(mysql_error());
}

mysql_select_db("db", $con);

$result = mysql_query("SELECT * FROM person");

echo '<table border="1">
<tr>
<th><input type="checkbox" name="checkboxA" value="checkbox" onclick="selector()"></th>
<th>First Name</th>
<th>Last Name</th>
</tr>';

?>

<script language="javascript">
function selector()
{
var count="<?php
$rowAmount = mysql_num_rows($result);
echo "$rowAmount";
?>";
var check = document.form1.checkboxA.checked;
if (check == true)
{
for (i=0;i<=count;i++)
{
document.form1.checkboxB[i].checked = true;
}
}
if (check == false)
{
for (i=0;i<=count;i++)
{
document.form1.checkboxB[i].checked = false;
}
}
}
function stopError()
{
return true;
}
window.onerror=stopError;
</script>

<?php

while($row = mysql_fetch_array($result))
{
  echo '<tr>';
  echo '<td><input type="checkbox" name="checkboxB" value="checkbox"></td>';
  echo '<td>'.$row['FirstName'].'</td>';
  echo '<td>'.$row['LastName'].'</td>';
  echo '</tr>';
}
echo '</table>';

mysql_close($con);
?>

</form>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.