Reputation: 566
I've got a bunch of checkboxes, I would like to restrict the user to check the checkboxes based on selectbox value.
for example, if user selects value - 3 in selectbox, then he can only check 3-checkboxes(any three)
Demo: Fiddle
HTML
<select id="count">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select><br/><br/>
<div class="checkbox">
<input id="checkbox-1" type="checkbox" name="Data1" value="option1" />
<label for="checkbox-1">HTML</label>
<br />
<input id="checkbox-2" type="checkbox" name="Data2" value="option2" />
<label for="checkbox-2">CSS</label>
<br />
<input id="checkbox-3" type="checkbox" name="Data3" value="option3" />
<label for="checkbox-3">HTML</label>
<br />
<input id="checkbox-4" type="checkbox" name="Data4" value="option4" />
<label for="checkbox-5">CSS</label>
<br />
<input id="checkbox-5" type="checkbox" name="Data5" value="option5" />
<label for="checkbox-5">HTML</label>
<br />
<input id="checkbox-6" type="checkbox" name="Data6" value="option6" />
<label for="checkbox-6">CSS</label>
</div>
How can i do this? Please can anyone help me out?
Upvotes: 3
Views: 1845
Reputation: 17171
DEMO: http://jsfiddle.net/HNmhL/23/
// Cache the selector
var checkBoxes = $('input[type=checkbox]');
checkBoxes.click(function() {
validateCheckboxes();
});
$('#count').change(function() {
// Only neave the first N items checked (where N = number of items allowed)
checkBoxes.filter(':checked:gt(' + ($(this).val() - 1) + ')').attr('checked', false);
validateCheckboxes();
});
function validateCheckboxes() {
// If the number of checked items exceeds the number allowed
if (checkBoxes.filter(':checked').length >= $('#count').val()) {
// Disable all un-checked boxes...
checkBoxes.not(':checked').attr('disabled', true);
} else {
// We haven't hit out limit yet; make sure the checkboxes are still enabled
checkBoxes.attr('disabled', false);
}
};
Upvotes: 3
Reputation: 232
This can be done in a single condition check with very minimal code :
$('input[type=checkbox]').on('click', function(event){
if($('div.checkbox input[type=checkbox]:checked').length > $('#count').val())
{
event.preventDefault();
}
});
Check out this fiddle example.
Upvotes: 0
Reputation: 4081
Use this
$('input[id^="checkbox-"]').hide();
$('select').on('change', function (e) {
var valueSelected = this.value;
for(i=1;i<=valueSelected;i++)
{
$('#checkbox-' + i).show();
}
});
Upvotes: 0
Reputation: 787
If you mean option val = 3 -> can check 3 checkboxes, then try this http://jsfiddle.net/HNmhL/9/
Javascript
$(document).ready(function(){
$('#count').on('change', function(){
$('input[type=checkbox]').prop('checked', false);
});
$('input[type=checkbox]').on('change', function(){
if($('input[type=checkbox]:checked').length > $('#count').val()){
$(this).prop('checked', false);
}
});
});
Upvotes: 2