How can I enable input field generated in result of a loop from array along with checkbox. I trying to disable the generated input fields and enable the one only when particular corresponding checkbox is checked. I’ve tried to follow this example enable disable inputs text with its corresponding checkbox jquery but couldn’t help my self.
$voucher array:
Array ( [7] => 95976X7F545 [9] => C53DVEFCC )
SOURCE:
<?php foreach ($voucher as $vou) { if($vou['payment_voucher_code']!=''){?> <div class="col-lg-3"> <span class="input-group-addon"> <input type="checkbox" id="chk"></span> <div> <input name="ex_code[<?php echo $vou['payment_voucher_id'];?>]" id="ex_code" value="<?php echo $vou['payment_voucher_code'];?>" disabled /> </div> </div> <?php } } ?>
HTML:
<div class="col-lg-3"> <span class="input-group-addon"> <input type="checkbox" id="chk"> </span> <div> <input name="ex_code" value="95976X7F545" disabled="disabled"> </div> </div> <div class="col-lg-3"> <span class="input-group-addon"> <input type="checkbox" id="chk"> </span> <div> <input name="ex_code" value="C53DVEFCC" disabled="disabled"> </div> </div>
JS:
$('#chk').change(function() { $('#ex_code').attr('disabled',!this.checked) });
RESULT:
Advertisement
Answer
Can you slightly modify your code? You can try the below solution.
SOURCE :
<?php foreach ($voucher as $vou) { if($vou['payment_voucher_code']!=''){?> <div class="col-lg-3"> <span class="input-group-addon"> <input type="checkbox" id="chk_<?php echo $vou['payment_voucher_id'];?>" name="chk[]"></span> <div> <input id="ex_code_<?php echo $vou['payment_voucher_id'];?>" name="ex_code[]" value="<?php echo $vou['payment_voucher_code'];?>" disabled /> </div> </div>
This will produce the HTML :
<div class="col-lg-3"> <span class="input-group-addon"> <input type="checkbox" id="chk_1" name="chk[]" /> </span> <div> <input name="ex_code_1" name="ex_code[]" value="95976X7F545" disabled="disabled" /> </div> </div> <div class="col-lg-3"> <span class="input-group-addon"> <input type="checkbox" id="chk_2" name="chk[]" /> </span> <div> <input name="ex_code_2" name="ex_code[]" value="C53DVEFCC" disabled="disabled" /> </div> </div> <?php } } ?>
And finally your JS will be :
$(':checkbox').change(function() { var chk_id = $(this).attr('id'); var id = chk_id.split("_"); var real_id = id[1]; if($("#chk_"+real_id).is(':checked')){ $("#ex_code_"+real_id).prop('disabled', false); } else { $("#ex_code_"+real_id).prop('disabled', true); } });
Hope this will help. Let me know if any issue.