joergi1988 joergi1988 - 5 months ago 20
Javascript Question

If Checkbox checked, only allow the next Checkbox to check

I make a Table with php function

<table width='400' border='0' cellpadding='2' cellspacing='0' id='booking'>
<tr>
<th width='150' align='left'>Start</th>
<th width='150' align='left'>End</th>
<th width='150' align='left'></th>
<th width='20' align='left'>reserv</th>
</tr>
<tr>
<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
</tr>


At the end i make td's with times and dates. in the last is one checkbox.

This i make around 10 times:

<tr>
<td>" . $start . "</td>\r\n
<td>" . date("H:i:s", $finish_time) . "</td>\r\n
<td>" . $this->cost_currency_tag . number_format($this->cost_per_slot, 2) . "</td>
<td width='110'>
<input data-val='".$start."-".date("H:i:s", $finish_time)."' class='fields' type='checkbox'>
</td>
</tr>";


I will make when i check a checkbox jquery allow only to check the NEXT checkbox. all other disabled. And when i check the next, it must be allow to check the next of this.

I have tried with this

$('.fields input[type=checkbox]').click(function(){
var obj = $(this).siblings('input[type=text]');
obj.attr('disabled', !obj.attr('disabled'));
})


But i do not get it work.. i have tried also with '.next'...
Can anyone help?

Answer

Use this code

$(".fields").change(function(){
    var index = $(this).index() + 1;
    $(".fields").attr("disabled", true);  
    $(".fields:lt("+ index +")").attr("disabled", false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="fields" />
<input type="checkbox" class="fields" />
<input type="checkbox" class="fields" />
<input type="checkbox" class="fields" />
<input type="checkbox" class="fields" />

Comments