您好我正在尝试添加一些功能,只允许用户一次最多选择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>
答案 0 :(得分: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>
答案 1 :(得分: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>
答案 2 :(得分: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个复选框后删除并勾选。是否可以添加 $(本).removeAttr( “检查”); 到第一个if语句而不是添加另一行代码?