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).

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);
    }
});

      

+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');

      



Demo: http://jsfiddle.net/tusharj/t01a9cxL/1/

+5


source


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


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


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

      

Fiddle

+1


source


You can get the same result with less code like this:

Updated script

// 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