Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

});
like image 967
Hayi Avatar asked Jun 23 '15 13:06

Hayi


1 Answers

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.

like image 199
Rory McCrossan Avatar answered Nov 08 '22 14:11

Rory McCrossan