Jquery checkbox checked when page loads

brunodd picture brunodd · May 28, 2015 · Viewed 36.9k times · Source

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

Answer

Tushar picture Tushar · May 28, 2015

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/