Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery checkbox checked when page loads

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);
    }
});
like image 882
brunodd Avatar asked May 28 '15 14:05

brunodd


People also ask

How do you checkbox is checked or not in jQuery on page load?

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

How do you check whether checkbox is checked or not?

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.


2 Answers

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/

like image 175
Tushar Avatar answered Oct 18 '22 11:10

Tushar


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);
    }
});
like image 23
George Avatar answered Oct 18 '22 12:10

George