Reputation: 119
I wanna say i rarely work with javascript. It's never been my thing and it probably never will be, so i'm sorry for my lack of knowledge to this language.. Which is why my question is so humiliating.
I found this code online:
function checkboxlimit(checkgroup, limit){
var checkgroup=checkgroup
var limit=limit
for (var i=0; i<checkgroup.length; i++){
checkgroup[i].onclick=function(){
var checkedcount=0
for (var i=0; i<checkgroup.length; i++)
checkedcount+=(checkgroup[i].checked)? 1 : 0
if (checkedcount>limit){
alert("You can check a maximum of "+limit+" boxes.")
this.checked=false
}
}
}
}
<script type="text/javascript">
checkboxlimit(document.forms.checkform.weapon[], 2)
</script>
And it looks pretty basic to me. Nothing speciel here. But, my problem is that i'm trying to find the checkbox through the name weapon[], which i'm required to as i'm outputting multiple checkboxes as weapon[] for array's. Now my question is, how i'll make this work with this stupid little error.
To sum up: My problem is that my checkboxes are named weapon[] (name="weapon[]") instead of (name="weapon"), as an array, and therefor the js wont recognize it.
Upvotes: 0
Views: 2832
Reputation: 2968
Are you looking for something like this?
$(':checkbox[name=weapon]').on('click',function(){
var checkedBoxlength=$(':checkbox[name=weapon]:checked').length;
if(checkedBoxlength>2){
alert('You can check a maximum of 2 boxes.');
return false;
}
});
--- Edit
Just made a jquery plugin just for limiting how many chekboxes you check.
(function( $ ){
$.fn.LimitCheckableNumber = function( options ) {
var settings = $.extend( {
'nr' : 1,
}, options);
return this.each(function() {
var $this=$(this),
thisName=$this.attr('name');
$this.on('click',function(){
var count=$(":checked[name='"+thisName+"']").length;
if(count>settings.nr){
alert('You can check a maximum of '+settings.nr+' boxes. ');
return false;
};
});
});
};
})( jQuery );
Upvotes: 2
Reputation: 4934
You can't use the []
when using dot notation. Switch to treating it like an associative array.
checkboxlimit(document.forms.checkform['weapon[]'], 2)
Works just fine.
Also, you don't need to redefine checkgroup
and limit
. You can just use them as the arguments.
Upvotes: 1