使用JavasScript检查PHP表单中的复选框


using JavasSript to check checkboxes in PHP form

嗨,我正在尝试添加一些功能,它只允许用户一次选择多达4个复选框,但失败得很惨。。。php和javascript似乎不能很好地协同工作!

我的PHP代码是:

<?php
echo "<form method='post' name='time' action='timeinsert.php'>";
echo "<td><input type='checkbox' `name='$displayTime2'onclick='KeepCount()'></td>";
echo "</form>";
?>

我的Javascript代码是:

<script language="JavaScript">
<!--`
function KeepCount() {
var NewCount = 0
if (document.time.<?php"$displayTime2"?>.checked)
{NewCount = NewCount + 1}
f (NewCount == 4)
{
alert("Pick maximum of 4 time slot's Please")
document.time; return false;`
}
//-->
</script>

使用jQuery:

<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'>
</script>
<script type='text/javascript'>
    $(function() {
        $('input[type=checkbox]').click(function () {
            var count = $('input[type=checkbox]:checked').length;   
            if (count > 4) alert('Pick maximum of 4 time slots please!');
        });
    });
</script>
<?php
    echo "<form method='post' name='time' action='timeinsert.php'>";
    echo "<td><input type='checkbox' name='$displayTime2'></td>";
    echo "</form>";
?>

更新:为了防止点击4次后发生进一步的检查,你可以这样做:

<script type='text/javascript'>
    $(function() {
        $('input[type=checkbox]').click(function () {
            var count = $('input[type=checkbox]:checked').length;   
            if (count > 4) {
                $(this).removeAttr('checked');
                alert('Pick maximum of 4 time slots please!');
            }
        });
    });
</script>
<script language="JavaScript">    
    var NewCount = 0;
    function KeepCount() 
    {
      if(NewCount <= 4)
      {
          if (document.time.<?php echo $displayTime2; ?>.checked)
          { 
               NewCount = parseInt(NewCount)+1;
          }
      }
      else
      {
         alert("Pick maximum of 4 time slot's Please");   
         return false;  
      }
    }
</script>

好的,我现在已经编辑了Stefan的代码,并提出了:

<script type='text/javascript' src='includes/jquery-1.9.1.min.js'>
</script>
<script type='text/javascript'>
    $(function() {
        $('input[type=checkbox]').click(function () {
            var count = $('input[type=checkbox]:checked').length;   
            if (count > 4) alert('Pick maximum of 4 time slots please!');
        if (count > 4) $(this).removeAttr("checked");
        });
    });
</script>

这会提醒用户,并在选中4个复选框后删除和勾选。是否可以添加$(this).removeAttr("已选中");添加到第一个if语句,而不是添加另一行代码?