0

嗨,我正在尝试添加一些功能,该功能只允许用户一次最多选择 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>
4

3 回答 3

0
<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>
于 2013-02-15T12:24:24.313 回答
0

使用 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>
于 2013-02-15T13:19:16.700 回答
0

好的,我现在已经编辑了 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("checked"); 到第一个 if 语句而不是添加另一行代码?

于 2013-02-15T13:56:25.830 回答