简体   繁体   中英

Javascript checkbox Validation not working in php

I'm struggling with this validation of a checkbox and can't seem to understand where it's going wrong. Any help would be fantastic. Because it's pulling from MySQL as an array, i'm not sure if this is where I am going wrong.

<script language="JavaScript" type="text/javascript">
function checkform ( form )
{
  if(!form.check_box_delete[].checked) {
        alert('Please check at least one of the options.');
        return false;
    }
    return true;
}
</script>

Here is the code for the body:

<form name="form" method="post" action="loan_checkedIn.php" onsubmit="return checkform(this);">
<?php
echo "<table border='1' align='center' width='900'>
<tr>
<th bgcolor='#00a3e0'><font face='Arial'>Select</font></th>
<th bgcolor='#00a3e0'><font face='Arial'>Customer</font></th>
<th bgcolor='#00a3e0'><font face='Arial'>Make</font></th>
<th bgcolor='#00a3e0'><font face='Arial'>Model</font></th>
</tr>";

$results = mysql_query("SELECT * FROM loan WHERE email='$email' AND status='Out'");
while($row1 = mysql_fetch_array($results))
  {
  echo "<tr>";
  echo "<td align='center'><input type='checkbox' name='check_box_delete[]' value='" . $row1['id'] . "'></td>";
  echo "<td align='center'><font face='Arial'>" . $row1['customer'] . "</font></td>";
  echo "<td align='center'><font face='Arial'>" . $row1['make'] . "</font></td>";
  echo "<td align='center'><font face='Arial'>" . $row1['model'] . "</font></td>";
  echo "</tr>";
  }
  echo "</table>";
  ?>

  <p align="center"><input type="submit" style="background-color:#00A3E0; color:#FFFFFF;" name="submit" value="Return Equipment"></p>
  </form>   

You could loop through all element type=checkbox in the form.

   var element = form.elements;
   for (var i = 0, element; element = elements[i++];) {
    if (element.type === "checkbox" && element.selected === "selected")
        alert("it's an empty textfield");
    }

You have issue in javascript. change your code as below:

<script language="JavaScript" type="text/javascript">
function checkform ( form )
{  
  var checkboxs=form['check_box_delete[]'];
  var cheked=false;
  for(var i=0,l=checkboxs.length;i<l;i++)
  {
      if(checkboxs[i].checked)
      {
          cheked=true;
          break;
      }
  }
  if(!cheked)
  {
    alert('Please check at least one of the options.');
        return false;
  }  
    return true;
}
</script>

Also stop using deprected/removed mysql_ extension. use mysqli_ or PDO instead (with prepared query )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM