This is a pretty straightforward library function I've got here. I've had to build it in to about 3 different forms but I never heard of this kind of function anywhere else.
I'm trying to make it as readable and clear as possible, but I also am not too familiar with the best way to capture values in JavaScript. As far as I know, the following disableChecker
function allows me to capture the value arguments at declaration time so I can have many of these DisableIf
checks going simultaneously.
function disableChecker(checkSelector, disableValue, targetSelector) {
var optionValue = $(checkSelector).val();
if (optionValue === disableValue) {
$(targetSelector).prop("disabled", true); //Disable target
} else {
$(targetSelector).prop("disabled", false); //Enable target
}
}
function DisableIf(checkSelector, disableValue, targetSelector) {
$(checkSelector).on("change,keyup,blur", disableChecker(checkSelector, disableValue, targetSelector));
}
Usage:
<select id="disableSource">
<option value="0">Disable Next</option>
<option value="1">Enable Next</option>
</select>
<input type="text" id="disableTarget" />
<input type="text" id="disableTarget2" />
<script type="text/javascript">
//Please note that at this time, order is important!
DisableIf("#disableSource", "0", "#disableTarget");
DisableIf("#disableTarget", "Disable Next", "#disableTarget2");
DisableIf("#disableSource", "0", "#disableTarget2");
<script>