The script is working fine however I am wondering if there is a way to avoid the repetition in the code (DRY method).
Demo
JS code:
// Checkbox checked and input disbaled when page loads
$('#checkbox').prop('checked', true);
if ($('#checkbox').is(':checked') == true) {
$('#textInput').prop('disabled', true);
}
// Enable-Disable text input when checkbox is checked or unchecked
$('#checkbox').change(function() {
if ($('#checkbox').is(':checked') == true) {
$('#textInput').prop('disabled', true);
} else {
$('#textInput').val('').prop('disabled', false);
}
});
We can check the status of a checkbox by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') .
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
If you can't set the attributes by default in HTML
:
// Checkbox checked and input disbaled when page loads
$('#checkbox').prop('checked', true);
// Enable-Disable text input when checkbox is checked or unchecked
$('#checkbox').on('change', function() {
var value = this.checked ? $('#textInput').val() : '';
$('#textInput').prop('disabled', this.checked).val(value);
}).trigger('change');
Demo: http://jsfiddle.net/tusharj/t01a9cxL/1/
If every time the page is loaded you want the check box to be checked and the text box to be disabled it's better to do it in HTML
HTML
<input type="checkbox" id="checkbox" checked="true" />
<input type="text" id="textInput" disabled=""/>
JavaScript
// Enable-Disable text input when checkbox is checked or unchecked
$('#checkbox').change(function() {
if ($('#checkbox').is(':checked') == true) {
$('#textInput').prop('disabled', true);
} else {
$('#textInput').val('').prop('disabled', false);
}
});
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