Hayi
Hayi

Reputation: 6246

Customize redundant Checkbox input Jquery Code

i have this working code bellow and i think he is a little bit too long and redundant can i customize it ?

$( "#unique" ).click(function() {

    if ( $( this ).is(':checked') ) {
        $( ".lotud" ).show();
        $( "#add_lot" ).hide();
        $( "#lots_rows_contnr" ).hide();

        $(".lotud input").prop({disabled: false})
        $("#lots_rows_contnr input").prop({disabled: true})
    }
    else {
        $( ".lotud" ).hide();
        $( "#add_lot" ).show();
        $( "#lots_rows_contnr" ).show();

        $(".lotud input").prop({disabled: true})
        $("#lots_rows_contnr input").prop({disabled: false})
    }

});

Upvotes: 5

Views: 71

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337626

You can shorten it slightly through the use of ternaries, using the checked property on the DOMElement itself, joining selectors and using the checked property as the basis for the disabled property. Try this:

$("#unique").click(function() {
    $(".lotud").toggle(this.checked);
    $("#add_lot, #lots_rows_contnr").toggle(!this.checked);
    $(".lotud input").prop({ disabled: !this.checked });
    $("#lots_rows_contnr input").prop({ disabled: this.checked });
});

Which of the two versions, your original or the above, is more readable is a matter of opinion.

Upvotes: 6

Related Questions