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
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>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.