Javascript self-service feature

Hey guys, I have a couple bits of code that seem such that they can be compressed, but I'm not sure how to do this.

The code I have is

var checkForUnitReferred = function () {
    $("#LeadForm").toggle($("#Claim_UnitReferredNoNull").is(":checked"));
};
checkForUnitReferred();

$("#Claim_UnitReferredNoNull").change(function() {
    checkForUnitReferred();        
});

It basically checks if the checkbox is checked and displays the form, otherwise it hides it. I would prefer something like this

var checkForUnitReferred = (function() {
    $("#LeadForm").toggle($("#Claim_UnitReferredNoNull").is(":checked"));
})();

$("#Claim_UnitReferredNoNull").change(function() {
    checkForUnitReferred();        
});

I know this doesn't work, but I think something like that would be cleaner. Does anyone know a way to do this?

+3
source share
2 answers

How about this:

var checkForUnitReferred;

(checkForUnitReferred = function() {
    $("#LeadForm").toggle($("#Claim_UnitReferredNoNull").is(":checked"));
})();

$("#Claim_UnitReferredNoNull").change(function() {
    checkForUnitReferred();        
});

This is possible because the assignment operator ( =) returns the given value.

+5
source

, . .change() :

(function checkForUnitReferred() {
    $("#LeadForm").toggle($("#Claim_UnitReferredNoNull").is(":checked"));
})();

$("#Claim_UnitReferredNoNull").change(checkForUnitReferred);
+2

Source: https://habr.com/ru/post/1784089/


All Articles