问题
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?
回答1:
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
}
});
});
回答2:
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>
回答3:
$(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/
回答4:
$("input[type=checkbox][checked]").each(
function() {
$("#sr").attr("disabled", "disabled")
}
);
回答5:
You can make it disabled = "disabled"
来源:https://stackoverflow.com/questions/7419383/make-field-readonly-checkbox-jquery