限制复选框基于值javascript

时间:2012-06-27 17:08:34

标签: javascript jquery html javascript-events

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

<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语句而没有运气!

2 个答案:

答案 0 :(得分: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);
    }
});
});​

答案 1 :(得分:0)

 lastChecked.splice(lastChecked.indexOf(this), 1);
}

}); });