Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript named, self-calling function

I have a couple bits of code that seem like they could be condensed but I'm not sure how.

The code I have is this

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

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

It basically checks if a checkbox is checked and displays a form, otherwise it hides it. What I would rather have is 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. Anyone know of a way to accomplish this?

like image 378
Jimmy Avatar asked Jul 27 '26 14:07

Jimmy


1 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 value set.

like image 116
lonesomeday Avatar answered Jul 29 '26 04:07

lonesomeday