Jquery checkbox checked on page load
The script works fine, but I am wondering if there is a way to avoid repeating the code (DRY method).
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);
}
});
+3
source to share
5 answers
If you cannot set the default attributes to 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');
+5
source to share
If every time the page is loaded you want the checkbox to be checked and the textbox 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);
}
});
+2
source to share
Separate your logic into a reusable function:
function checkboxStatus() {
if ($('#checkbox').is(':checked') == true) {
$('#textInput').prop('disabled', true);
} else {
$('#textInput').val('').prop('disabled', false);
}
}
// Checkbox checked and input disbaled when page loads
$('#checkbox').prop('checked', true);
checkboxStatus();
// Enable-Disable text input when checkbox is checked or unchecked
$('#checkbox').change(checkboxStatus);
+1
source to share
Just do it like plain jquery in a lot of ways to do
$('#checkbox').prop( 'checked', true ); // when intially checked
$('#checkbox').change(function(){
$('#textInput').prop('disabled', $(this).is(':checked'));
if(!$(this).is(':checked')){
$('#textInput').val('')
}
}).change(); //intially trigger the event change
+1
source to share
You can get the same result with less code like this:
// Checkbox checked and input disbaled when page loads
$('#checkbox').prop('checked', true);
$('#textInput').prop('disabled', true);
// Enable-Disable text input when checkbox is checked or unchecked
$('#checkbox').change(function () {
var checked = $(this).is(':checked') == true;
$('#textInput').prop('disabled', checked);
});
+1
source to share