1

我试图根据值更改示例创建复选框限制:我有以下复选框

<input type="checkbox" name="checkbox2[]" onClick="setChecks(this)" value="`key`=<?php 
echo $rspatient['key']?>" class="chk" id="chk<?php echo $a++?>" />

我有很多复选框,因为这是一个循环...有些具有相同的值,而另一些则没有...无论如何都希望创建代码来防止具有不同值的复选框!

限制复选框数量的当前代码

<script>
 <!--
 //initial checkCount of zero 
 var checkCount = 0
 //maximum number of allowed checked boxes 
 var maxChecks = 3
 var d = document.getElementById('chk' + (j++));

 function setChecks(obj) {
     //increment/decrement checkCount 
     if (obj.checked) {
         checkCount = checkCount + 1
     } else {
         checkCount = checkCount - 1
     }
     //if they checked a 4th box, uncheck the box, then decrement checkcount and pop alert 
     if (checkCount > maxChecks) {
         obj.checked = false
         checkCount = checkCount - 1
         alert('you may only choose up to ' + maxChecks + ' options')
     }
 }
 // -->
</script>

我试图编辑最终的 if 语句,但没有成功!

4

2 回答 2

0

经过一番折腾后,我终于找到了一个可行的解决方案!

1 <input type="checkbox" value="1" /><br/>
2 <input type="checkbox" value="2" /><br/>
3 <input type="checkbox" value="3" /><br/>
1 <input type="checkbox" value="1" /><br/>
2 <input type="checkbox" value="2" /><br/>
3 <input type="checkbox" value="3" /><br/>
1 <input type="checkbox" value="1" /><br/>
2 <input type="checkbox" value="2" /><br/>
3 <input type="checkbox" value="3" /><br/>

$(function() {
var lastChecked = [];
$(':checkbox').change(function() {
    if (this.checked) {
        if (lastChecked.length && this.value != lastChecked[0].value) {
            this.checked = false;
            alert("the last box you checked has a different value");
        }
        else
        {
            lastChecked.unshift(this);
        }
    }
    else {
        lastChecked.splice(lastChecked.indexOf(this), 1);
    }
});
});​

​</p>

于 2012-07-14T15:10:09.573 回答
0
 lastChecked.splice(lastChecked.indexOf(this), 1);
}

}); });​</p>

于 2012-07-18T22:43:53.673 回答