I have this checkbox:
<input type="checkbox" name="suspended" id="s" value="<?php echo $udata['suspended']; ?>" <?php echo $suspended; ?>>
And this textarea:
<textarea name="suspendreason" id="sr" style="height:60px" class="field"><?php echo $udata['suspendreason']; ?></textarea>
My question is, how can I make the textarea READONLY whenever the #s checkbox is unchecked?
A checkbox HTML element doesn't have a "readonly" property. Consequently, the only way to make a checkbox appear to be "readonly" is to disable the control.
To make a textarea and input type read only, use the attr() method .
Just add onclick="return false" in your HTML code.
In checkboxes, for example, you can check them on or off (thus setting the CHECKED state) but you don't change the value of the field.
With your requirement, something like this:
$(document).ready(function(){
if($('#s:checked').length){
$('#sr').attr('readonly',true); // On Load, should it be read only?
}
$('#s').change(function(){
if($('#s:checked').length){
$('#sr').attr('readonly',true); //If checked - Read only
}else{
$('#sr').attr('readonly',false);//Not Checked - Normal
}
});
});
I recommend making it readonly and disabled.
$("#sr").attr('disabled', 'disabled');
$("#sr").attr('readonly', 'readonly');
simply because if someone is in Carat Browsing mode, rare, but yes I've had clients do this, they can edit the disabled fields.
And for the checkbox:
<script type="text/javascript">
$(document).ready(function () {
// check upon loading
if(!$("#s").is(:checked))
{
$("#sr").attr('disabled', 'disabled');
$("#sr").attr('readonly', 'readonly');
}
// event
$("#s").change(function () {
if(!$(this).is(:checked)) {
{
$("#sr").attr('disabled', 'disabled');
$("#sr").attr('readonly', 'readonly');
}
else
{
$("#sr").attr('disabled', '');
$("#sr").attr('readonly', '');
}
}
});
</script>
$(document).ready(function() {
$("#s").change(function() {
if (!this.checked) {
$("#sr").attr('disabled', 'disabled');
$("#sr").attr('readonly', 'true');
}
else {
$("#sr").removeAttr('disabled');
$("#sr").removeAttr('readonly');
}
});
//triger change event in case checkbox checked when user accessed page
$("#s").trigger("change")
});
Working demo - http://jsfiddle.net/cc5T3/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With