Reputation: 41
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<lable>Checkbox 1</lable>
<input type="checkbox" class="fields" checked/>
<br>
<lable>Checkbox 2</lable>
<input type="checkbox" class="fields" checked/>
<br>
<lable>Checkbox 3</lable>
<input type="checkbox" class="fields" checked />
<br>
<lable>Checkbox 4</lable>
<input type="checkbox" class="fields" checked/>
<br>
<lable>Checkbox 5</lable>
<input type="checkbox" class="fields" checked/>
$('[type=checkbox]').click(function() {
var $this = this;
if ($(this).is(':checked'))
return;
var uncheck = false;
$('[type=checkbox]').each(function() {
if (this === $this){
uncheck = true;
}
if (uncheck){
this.checked = false;
}
});
});
Once the any top checkbox is unchecked all below check boxes will unchecked automatically, but i want when any top check is checked next checkbox only should be enabled, when user check that box another checkbox should enable.
Upvotes: 1
Views: 138
Reputation: 36104
As per your last comment, you can add unlimited checkbox, if any checkbox unchecked from middle then next all checkbox will be disabled..
$('.fields').on('click', function() {
let nextChk = $(this).nextAll('.fields');
// checked
if( this.checked ){
// find the next checkbox and disabled it
if( nextChk.first().length )
nextChk.first().attr('disabled', false);
}
// unchecked
else{
// find all checkboxes, disable and check it
nextChk.each(function(){
$(this).attr('disabled', true);
$(this).prop('checked', false);
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Checkbox 1</label>
<input type="checkbox" class="fields" checked/>
<br>
<label>Checkbox 2</label>
<input type="checkbox" class="fields" checked/>
<br>
<label>Checkbox 3</label>
<input type="checkbox" class="fields" checked/>
<br>
<label>Checkbox 4</label>
<input type="checkbox" class="fields" checked/>
<br>
<label>Checkbox 5</label>
<input type="checkbox" class="fields" checked/>
Upvotes: 2
Reputation: 28196
This does at least part of the job (enabling the next checkbox):
var cbs=$('[type=checkbox]').click(function(){
let nxt=cbs.get(cbs.index(this)+1)
if (nxt) nxt.disabled=false;
}).slice(1).prop('disabled',true).end();
input:checkbox {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label>Checkbox 1
<input type="checkbox" class="fields"/></label>
<br>
<label>Checkbox 2
<input type="checkbox" class="fields"/></label>
<br>
<label>Checkbox 3
<input type="checkbox" class="fields"/></label>
<br>
<label>Checkbox 4
<input type="checkbox" class="fields"/></label>
<br>
<label>Checkbox 5
<input type="checkbox" class="fields"/></label>
</form>
Upvotes: 1